joh*_*y 5 2 c# reflection func
说我有一个功能如何在记录上设置属性
public void SetProperty<TRecord, TEnum>(TRecord item,
Func<TRecord, TEnum> property, string enumValue )
where TEnum : struct
where TRecord : class
{
TEnum enumType;
if (Enum.TryParse(enumValue, true, out enumType))
{
//How Do I set this?
property.Invoke(item) = enumType;
}
}
Run Code Online (Sandbox Code Playgroud)
我不想把它换成表达式.有人知道如何设置属性吗?
public void SetProperty<TRecord, TEnum>(TRecord item,
Action<TRecord, TEnum> property, string enumValue)
where TEnum : struct
where TRecord : class
{
TEnum enumType;
if (Enum.TryParse(enumValue, true, out enumType))
{
property(item, enumType);
}
}
Run Code Online (Sandbox Code Playgroud)
更好的方法...
public TEnum? AsEnum<TEnum>(string enumValue)
where TEnum : struct
{
TEnum enumType;
if (Enum.TryParse(enumValue, true, out enumType))
{
return enumType;
}
return default(TEnum);
}
Run Code Online (Sandbox Code Playgroud)
用法示例......
myObj.Prop = AsEnum<MyEnum>("value") ?? MyEnum.Default;
//versus
SetPropery<MyObject, MyEnum>(myobj, (r, e) => r.Prop = e, "value");
Run Code Online (Sandbox Code Playgroud)