动态铸造问题

Caf*_*dCM 2 c# casting overloading dynamic

我一直在寻找一个解决我遇到的问题的方法,一旦我认为我找到了修复它就行不通.问题是我有一个CustomAttriburte数组,我想将它们转换为它们的实际类型,所以我可以根据它们的类型将每个方法传递给不同的方法.例如:我有一个RangeAttribute和DisplayFormatAttribute的单独方法,我希望调用正确的方法.

我做了一个测试控制台应用程序,我有一个基类和2个子类,每个类都有各自的"DoSomething(T t)"方法.通过运行方法:"DoSomething(x as dynamic)"为我的数组中的每个元素调用正确的方法.

以下作品:

class Base{} 
class ChildA : Base {}
class ChildB : Base {}
class Program {
    static void Main(string[] args) 
    {
        Base[] c = { new ChildA(), new Base(), new ChildB() };
        Console.Out.WriteLine(DoSomething(c[0] as dynamic));
        Console.Out.WriteLine(DoSomething(c[1] as dynamic));
        Console.Out.WriteLine(DoSomething(c[2] as dynamic));
        Console.ReadLine();
     }
     static string DoSomething(Base b) { return "Base";}
     static string DoSomething(ChildA c) { return "ChildA";}
     static string DoSomething(ChildB c) { return "ChildB";}
}
Run Code Online (Sandbox Code Playgroud)

这导致我想要的输出:

ChildA
Base
ChildB
Run Code Online (Sandbox Code Playgroud)

所以这可行,但在我的实际应用程序中,我得到一个RuntimeBinderException

我的代码是:

class Seeder {
     public void Seed() {
              ... 
             CustomAttributeData[] custAtrData = propertyInfo.CustomAttributes.ToArray();
             for(int i = 0; i < custAtrData.Length; i++) {
                    custAtrData[i] = Behavior.Bug(custAtrData[i] as dynamic);
             }
     }
}
class Behavior {
       public static RangeAttribute Bug(RangeAttribute) {... } 
       public static DisplayAttribute Bug(DisplayAttribute) {...} 
       ... 
}
Run Code Online (Sandbox Code Playgroud)

异常说方法Bug的最佳重载有一些无效的参数,但只有一个参数,我已经验证了参数确实匹配Bug方法的重载.

那么为什么这个在我的测试应用程序中工作而不是实际的呢?

SLa*_*aks 6

CustomAttributeData 是一个单独的类,它包含有关程序集中属性的基本元数据.

它不运行实际的属性代码,也不是属性类的实例.

你想要的GetCustomAttributes(),它实例化并返回你的实际属性类.


此外,你应该避免使用dynamic那样的; 它很慢.

相反,您可以简单地使所有属性继承基类或接口,然后将这些方法放在属性类中,并通过基类型直接调用它们.