如果我有一个 propertyInfo 和带有此扩展变量的对象,我可以调用扩展方法吗?
我有一个扩展:
public static string GetTitle(this MyEnum myEnum)
{
switch (myEnum)
{
case MyEnum.One:
return "one";
case MyEnum.Two:
return "two";
default:
return "zero";
}
}
和枚举:
public enum MyEnum
{
Zero, One, Two
}
和类(class)
public class MyClass
{
public string A {get;set;}
public MyEnum B {get;set;}
}
当我得到这个类的PropertyInfo时,我需要调用一个扩展。 我尝试这样做
// .....
foreach(var prop in properties){
var value = prop.GetType().IsEnum ? prop.GetTitle() : prop.GetValue(myObj, null).ToString()
}
// .....
但是这不起作用。
我有几个不同的枚举和几个不同的扩展。我尝试获取值,而不管类型如何。
最佳答案
我的大学是对的,问题的代码完全不正确。 Prop 是 PropertyInfo对象,然后
prop.GetType().IsEnum
将始终返回 false。
首先您应该将此检查更改为
prop.GetValue(myObj, null).GetType().IsEnum
然后你可以像简单的静态方法一样调用扩展方法:
YourClassWithExtensionMethod.GetTitle((MyEnum)prop.GetValue(myObj, null))
完整的解决方案将类似于下一个代码:
foreach(var prop in properties)
{
var value = prop.GetValue(myObj, null).GetType().IsEnum ? YourClassWithExtensionMethod.GetTitle((MyEnum)prop.GetValue(myObj, null)) : prop.GetValue(myObj, null).ToString()
}
但是您应该确保您的属性值实际上转换为 MyEnum。最后我们将添加新的检查:
foreach(var prop in properties)
{
var value = prop.GetValue(myObj, null).GetType().IsEnum ? (prop.GetValue(myObj, null) is MyEnum ? YourClassWithExtensionMethod.GetTitle((MyEnum)prop.GetValue(myObj, null)) : ProcessGenericEnum(prop.GetValue(myObj, null)) ) : prop.GetValue(myObj, null).ToString()
}
现在你几乎不应该优化这行代码。仅检索一次值并分离 2 个条件。
foreach(var prop in properties)
{
var propertyValue = prop.GetValue(myObj, null);
if(propertyValue != null)
{
var value = propertyValue.GetType().IsEnum
? (propertyValue is MyEnum
? YourClassWithExtensionMethod.GetTitle((MyEnum) propertyValue)
: ProcessGenericEnum(propertyValue))
: propertyValue.ToString();
}
}
干得好!
关于c# - 如果我有 PropertyInfo 和带有此扩展变量的对象,我可以调用扩展方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34316777/