简体   繁体   English

Lambda传递的c#可重用属性

[英]c# reusable property to be called passed by lambda

I'm trying to write a method that would take an object with property name as a lambda parameter, and use it on passed object, but also use it on another, new object of the same type created inside that method. 我正在尝试编写一种方法,该方法将具有属性名称的对象作为lambda参数,并在传递的对象上使用它,但还要在该方法内部创建的相同类型的另一个新对象上使用它。

The goal is to use the same property on both objects. 目标是在两个对象上使用相同的属性。 The property name should be passed as a parameter to the method (lambda expression). 属性名称应作为参数传递给方法(lambda表达式)。

Let me show what I've written so far (doesn't compile): 让我展示一下到目前为止我写过的内容(尚未编译):

Object to be used: 使用对象:

public class ObjectMy
{
  public string Prop1 {get; set;}
}

Method in another class to be used with above object: 与上述对象一起使用的另一个类中的方法:

public class TestClass1
{
    public void DoSomethingOnProperty(Expression<Func<ObjectMy,string>> propertyName)
    {
        var object1 = new ObjectMy();
        var propertyNameProp = propertyName.Body as MemberExpression;
        propertyNameProp.Member = "Test string"; // error Member is readonly

        //DoSomethingOnProperty(object1.thesameproperty...)

    }
}

I want to set passed in method's name property of ObjectMy's instance to "Test string" and then recursively call DoSomethingOnProperty on another, new instance of ObjectMy, and use the same property name as given in the first call to DoSomethingOnProperty. 我想将传入的ObjectMy实例的name属性设置为“测试字符串”,然后在另一个新的ObjectMy实例上递归调用DoSomethingOnProperty,并使用与第一次调用DoSomethingOnProperty相同的属性名称。

I'd like to call it like 我想这样称呼

DoSomethingOnProperty(obj=>obj.Prop1);

Thanks. 谢谢。

Try changing your method like this: 尝试像这样更改方法:

public void DoSomethingOnProperty<T>(Expression<Func<T, dynamic>> propertyName) where T : class, new()
    {
        var object1 = Activator.CreateInstance(typeof(T));
        var methodName = (propertyName.Body as MemberExpression).Member.Name;
        var propertyInfo = typeof(T).GetProperty(methodName);
        typeof(T).GetProperty(methodName).SetValue(object1, Convert.ChangeType("Test string", propertyInfo.PropertyType));

        //DoSomethingOnProperty(object1.thesameproperty...)

    }

you could use it like 你可以像这样使用它

DoSomethingOnProperty<ObjectMy>(x => x.Prop1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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