【问题标题】:Can I call extension method if I have a PropertyInfo and object with variable for this extension?如果我有此扩展的 PropertyInfo 和带有变量的对象,我可以调用扩展方法吗?
【发布时间】:2015-12-16 16:08:38
【问题描述】:

如果我有一个用于此扩展的 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
}

和班级

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()
 }
// .....

但它不起作用。

我有几个不同的枚举和几个不同的扩展。无论类型如何,我都会尝试获取值。

【问题讨论】:

  • 请提供它不起作用的详细信息。
  • 类型本身不存在扩展方法,它们以不同的方式“粘合”到它。无论哪种方式,PropertyInfo 对象上都不存在扩展方法(或任何特定于类型的方法)。
  • prop 是什么类型?我猜这不是MyEnum

标签: c# .net reflection enums propertyinfo


【解决方案1】:

我的大学是正确的,问题的代码完全不正确。 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();
    }
}

干得好!

【讨论】:

  • 除了prop 几乎肯定不是MyEnum。它可能是一个PropertyInfo 实例。你需要WhatEver.GetTitle((MyEnum)prop.GetValue(myObj, null)) 才能工作。
  • TY 为您的修复。
  • 但是,如果我不知道枚举的类型是什么?因为我得到一个对象,而我对它的属性一无所知。
  • 还要注意GetValue(myObj, null)之后的空引用
  • @VadimMartynov 非常感谢您的解释。当我没有有关枚举类型的信息时,我可以更改此代码吗?如果我得到另一个枚举类型的对象,我需要检查每种情况的属性类型吗?我从 Object 类型的变量中获取属性信息,如果变量中有另一个枚举变量,我需要像我的第一个一样使用另一个扩展。
猜你喜欢
  • 1970-01-01
  • 2011-11-21
  • 2021-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-20
  • 1970-01-01
相关资源
最近更新 更多