根据我的理解,c#中的get方法得到的值应该是一个副本,也就是说,如果属性是一个子类的话,会得到类的克隆,调用克隆类的方法对原类应该是不起作用的
但是实际上好像并非如此,比如c#中的
comboBox1.Items.Clear();
Items返回一个ObjectCollection类,的确可以清空
而我通过自己测试发现不能修改指向结构体的属性,因为它并不是变量(的确)
我尝试了添加ref关键字,但是被报错(没有系统地学习c#,如果有低级错误请轻喷)
求原理QWQ
另外:我也用c++造了个property的轮子,如果方便可以看看并告诉我如何修改可以取得上述效果吗?十分感谢!
代码如下:
#include<functional>
enum class PropertyMode {
Read, Write, ReadWrite
};
template<typename T, PropertyMode PM>
class Property {
private:
Property() = delete;
Property(Property&) = delete;
};
template<typename T>
class Property<T, PropertyMode::Read> {
private:
std::function<T()> Get;
public:
Property() {
Get = nullptr;
}
Property(std::function<T()> Getter) {
Get = Getter;
}
Property(T& value) {
Get = [&]() {return value; };
}
operator T() {
return Get();
}
};
template<typename T>
class Property<T, PropertyMode::Write> {
private:
std::function<void(T)> Set;
public:
Property() {
Set = nullptr;
}
Property(std::function<void(T)> Setter) {
Set = Setter;
}
Property(T& value) {
Set = [&](T _value) {value = _value; };
}
void operator =(T value) {
Set(value);
}
};
template<typename T>
class Property<T, PropertyMode::ReadWrite> {
private:
std::function<T()> Get;
std::function<void(T)> Set;
public:
Property() {
Get = nullptr;
Set = nullptr;
}
Property(std::function<T()> Getter, std::function<void(T)> Setter) {
Get = Getter;
Set = Setter;
}
Property(T& value) {
Get = [&]() {return value; };
Set = [&](T _value) {value = _value; };
}
operator T() {
return Get();
}
T operator =(T value) {
Set(value);
return Get();
}
};
#pragma region Demo
#if 0
#include<iostream>
using std::cout;
using std::endl;
class A {
private:
int value;
public:
A() {
value = 0;
Value = Property<int, PropertyMode::ReadWrite>(
[this]() {return value; },
[this](int v) {value = v; }
);
}
Property<int, PropertyMode::ReadWrite> Value;
};
int main() {
A a;
for (int i = 1; i <= 10; i++) {
cout << (a.Value = a.Value + i) << endl;
}
}
#endif
#pragma endregion