指向 getters/setters 的字典
Dictionary that points to getters/setters
是否可以创建指向 getter 和 setter 的字典?
例如:
public class test
{
public Dictionary<string, int> pointer = new Dictionary<string,int>()
{
{ "a", a }
}; // the goal is to do pointer["a"] = someInt or print(pointer[a])
public int a { get { return b;} set { b = 2; } }
public int b;
}
很可能您实际上并没有尝试将 getter 和 setter 放入字典中,而是您正在尝试通过名称访问属性。 This is easily possible through Reflection. 如果这是你的问题,你应该将其标记为重复并关闭问题。
但是,您实际问题的答案是肯定的。可以制作指向 getter 和 setter 的字典。您将需要使用一些 lambda 编程。这是一种方法:
public class test
{
public Dictionary<string, GetSet<int>> pointer;
public test()
{
pointer = new Dictionary<string, GetSet<int>>()
{
{ "a", new(()=>a,i=>a = i) }
};
}
public int a { get { return b; } set { b = 2; } }
public int b;
}
public class GetSet<T>
{
private readonly Func<T> _get;
private readonly Action<T> _set;
public GetSet(Func<T> get, Action<T> set)
{
_get = get;
_set = set;
}
public T Get() => _get();
public void Set(T value) => _set(value);
}
用法:
var test = new test();
var property = test.pointer["a"];
var value = property.Get();//returns the value of test.a
property.Set(3);//sets test.a to 3
是否可以创建指向 getter 和 setter 的字典?
例如:
public class test
{
public Dictionary<string, int> pointer = new Dictionary<string,int>()
{
{ "a", a }
}; // the goal is to do pointer["a"] = someInt or print(pointer[a])
public int a { get { return b;} set { b = 2; } }
public int b;
}
很可能您实际上并没有尝试将 getter 和 setter 放入字典中,而是您正在尝试通过名称访问属性。 This is easily possible through Reflection. 如果这是你的问题,你应该将其标记为重复并关闭问题。
但是,您实际问题的答案是肯定的。可以制作指向 getter 和 setter 的字典。您将需要使用一些 lambda 编程。这是一种方法:
public class test
{
public Dictionary<string, GetSet<int>> pointer;
public test()
{
pointer = new Dictionary<string, GetSet<int>>()
{
{ "a", new(()=>a,i=>a = i) }
};
}
public int a { get { return b; } set { b = 2; } }
public int b;
}
public class GetSet<T>
{
private readonly Func<T> _get;
private readonly Action<T> _set;
public GetSet(Func<T> get, Action<T> set)
{
_get = get;
_set = set;
}
public T Get() => _get();
public void Set(T value) => _set(value);
}
用法:
var test = new test();
var property = test.pointer["a"];
var value = property.Get();//returns the value of test.a
property.Set(3);//sets test.a to 3