c# 可重用 属性 由 lambda 调用传递
c# reusable property to be called passed by lambda
我正在尝试编写一个方法,将名称为 属性 的对象作为 lambda 参数,并将其用于传递的对象,但也将其用于另一个相同类型的新对象在该方法中创建。
目标是在两个对象上使用相同的 属性。 属性 名称应作为参数传递给方法(lambda 表达式)。
让我展示一下我到目前为止所写的内容(无法编译):
要使用的对象:
public class ObjectMy
{
public string Prop1 {get; set;}
}
另一个class中的方法与上述对象一起使用:
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...)
}
}
我想将 ObjectMy 实例的传入方法名称 属性 设置为 "Test string"
然后在 ObjectMy 的另一个新实例上递归调用 DoSomethingOnProperty,并使用与第一次调用 DoSomethingOnProperty 时相同的 属性 名称。
我想这样称呼它
DoSomethingOnProperty(obj=>obj.Prop1);
谢谢。
试试这样改变你的方法:
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...)
}
你可以像这样使用它
DoSomethingOnProperty<ObjectMy>(x => x.Prop1);
我正在尝试编写一个方法,将名称为 属性 的对象作为 lambda 参数,并将其用于传递的对象,但也将其用于另一个相同类型的新对象在该方法中创建。
目标是在两个对象上使用相同的 属性。 属性 名称应作为参数传递给方法(lambda 表达式)。
让我展示一下我到目前为止所写的内容(无法编译):
要使用的对象:
public class ObjectMy
{
public string Prop1 {get; set;}
}
另一个class中的方法与上述对象一起使用:
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...)
}
}
我想将 ObjectMy 实例的传入方法名称 属性 设置为 "Test string" 然后在 ObjectMy 的另一个新实例上递归调用 DoSomethingOnProperty,并使用与第一次调用 DoSomethingOnProperty 时相同的 属性 名称。
我想这样称呼它
DoSomethingOnProperty(obj=>obj.Prop1);
谢谢。
试试这样改变你的方法:
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...)
}
你可以像这样使用它
DoSomethingOnProperty<ObjectMy>(x => x.Prop1);