简体   繁体   中英

c# modify a generic property

I have a viewmodel with 2 properties of the same type (bool). I like to have a function which sets one of the properties to a bool value. Let's say you have a IsReadonly property.

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. Reason: If another developer refactors the project and renames IsReadonly, the string wouldn't get updated. 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. Standard practice is to have a getter and setter for each value so you can control access to them. Having a getter and setter for both variables defeats the general purpose of having getters and setters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM