c# - 如果我有 PropertyInfo 和带有此扩展变量的对象,我可以调用扩展方法吗?

标签 c# .net reflection enums propertyinfo

如果我有一个 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/

相关文章:

java - Scala 反射在运行时使用方法的返回类型进行强制转换

c# - 在运行时将所有事件处理程序从一个控件复制到另一个控件

c# - MVC 母版页动态数据

c# - 如何创建一个在其他控件之上工作的透明控件?

.net - 多个 .NET 进程内存占用

c# - 在 asp.net 中验证密码

c# - 使用反射的比较运算符

c# - 为什么下面的电话是模棱两可的?

c# - 从实现者调用接口(interface)扩展方法在 C# 中很奇怪

mysql - 如何知道给定的数据是否已存在于数据库中?