新建User类:
public class User
{
public int Id { get; set; }
public string Name { get; set; }
}
实例:
User user = new User();
Action<User, string> setAction = (Action<User, string>)Delegate.CreateDelegate(typeof(Action<User, string>), typeof(User).GetProperty("Name").GetSetMethod());//得到Name属性的set_Name方法 委托
setAction(user, "czj");//Name="czj"
Func<User, string> getFunc = (Func<User, string>)Delegate.CreateDelegate(typeof(Func<User, string>), typeof(User).GetProperty("Name").GetGetMethod());得到Name属性的get_Name方法 委托
string name = getFunc(user);//"czj"
如果场景中有需要大量循环使用反射设置或者得到属性的情况,可以使用该方法,性能比反射GetValue/SetValue 要高