[英]c# modify a generic property
I have a viewmodel with 2 properties of the same type (bool). 我有一个具有2个相同类型(布尔型)属性的viewmodel。 I like to have a function which sets one of the properties to a bool value.
我喜欢有一个将属性之一设置为bool值的函数。 Let's say you have a IsReadonly property.
假设您有一个IsReadonly属性。
public void SetReadOnly(MyViewModel vm, bool newVal)
{
vm.IsReadOnly = newVal;
}
Now i want to make it more generic, and have a function for both: 现在,我想使其更通用,并具有两者的功能:
public void SetBooleanProperty(MyViewModel vm, bool newVal, ?bool? myProperty)
{
vm.myProperty = newVal; // sure this is an error, myProperty doesn't exist in the viewmodel. But that shows the way i like to have.
}
I started this approach: 我开始这种方法:
public void SetBooleanproperty<TProp>(MyViewModel vm, bool newVal, TProp myProperty)
{
vm.??? = newVal;
}
I don't like to use a function GetPropertyByName("IsReadonly") which i think is available somewhere in the reflection classes from .Net. 我不喜欢使用函数GetPropertyByName(“ IsReadonly”),我认为该函数在.Net的反射类中可用。 Reason: If another developer refactors the project and renames IsReadonly, the string wouldn't get updated.
原因:如果另一个开发人员重构项目并重命名IsReadonly,则不会更新字符串。 Is there a solutiuon for this ?
有解决方案吗?
You're trying to use reflection without using reflection. 您正在尝试使用反射而不使用反射。 I don't think you're going to find an answer.
我认为您不会找到答案。 There are no generics against properties in the language.
语言中没有针对属性的泛型。
Closest thing I can think of, which is awful, would be to pass in an action - this is pretty ridiculous, but it works. 我能想到的最糟糕的事情是通过一个动作-这很荒谬,但是可以。 Please don't do this:
请不要这样做:
public void PerformAction(MyViewModel vm, bool newVal,
Action<MyViewModel, bool> action)
{
action(vm, newVal);
}
PerformAction(someViewModel, true, (vm, b) => vm.IsReadOnly = b);
That's not a good way to do that. 那不是这样做的好方法。 You don't want to combine getters and setters.
您不想结合使用getter和setter。 Standard practice is to have a getter and setter for each value so you can control access to them.
标准做法是为每个值都有一个getter和setter,以便您可以控制对它们的访问。 Having a getter and setter for both variables defeats the general purpose of having getters and setters.
对于这两个变量都具有吸气剂和吸气剂会破坏使用吸气剂和吸气剂的总体目的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.