简体   繁体   English

尝试调用调用会导致“对象与目标类型不匹配”

[英]Trying to call an invoke results in “Object does not match target type”

I'm trying to do a bit of factoring on my use of a series of Enums defined in .net 我尝试对使用.net中定义的一系列枚举进行一些因素分析

    private static String GetSystemTranslatedField(Type enumtype, int? val) {
        if (val == null)
            return "";

        int value = (int)val;
        String tempstr;
        if (Enum.IsDefined(enumtype, value))
        {
            tempstr = (String) enumtype.GetMethod("ToString",Type.EmptyTypes).Invoke(val,null); 
            //equivalent to ((enumtype)val).ToString();
        }
    }

The problem is that when trying to run this, i get the infamous System.Reflection.TargetException: Object does not match target type. 问题是,当尝试运行此代码时,我得到了臭名昭著的System.Reflection.TargetException: Object does not match target type.

As an extra question, is there a way to change the signature of my method so that only types deriving from Enum are accepted? 还有一个问题,是否有办法更改我方法的签名,以便仅接受从Enum派生的类型? It's not a big concern but i got curious about type restriction and couldn't find anything. 这不是一个大问题,但我对类型限制感到好奇,找不到任何东西。

Enum is a class , so you can set that as your base for method signature and avoid reflection entirely . Enum是一个类 ,因此您可以将其设置为方法签名的基础, 并完全避免反射 Try: 尝试:

    private static String GetSystemTranslatedField(Enum enumtype, int? val) {
        if (!val.HasValue)
            return "";

        String tempstr;
        if (Enum.IsDefined(enumtype, val.Value))
        {
            tempstr = ((enumtype)val.Value).ToString(); 
        }

        ... // Rest of your code here
    }

Note that I cleaned your method up a bit, mainly cosmetic stuff. 请注意,我整理了一下您的方法,主要是修饰性的东西。

You are trying to call ToString coming from an enum type on an Int32 which is causing an exception in the Reflection API. 您正在尝试从Int32上的枚举类型调用ToString ,这会在Reflection API中引起异常。

If you want to get the identifier related to a value, use Enum.GetName which will work on int's as well (although the documentation does not seem to indicate this): 如果要获取与值相关的标识符,请使用Enum.GetName ,它也可以在int上使用(尽管文档似乎并未指出这一点):

if (Enum.IsDefined(enumtype, value))
{
    tempstr = Enum.GetName(enumType, value);
}

In fact it will return the empty string if the value is not defined, so that if could be removed as well (depending on what is in the rest of the code): 实际上,如果未定义该值,它将返回空字符串,以便也可以将其删除(取决于代码其余部分的内容):

tempstr = Enum.GetName(enumType, value);

C# does not allow generic constraints to Enum derived types. C#不允许对Enum派生类型进行一般约束。 It is doable on a theoretical level (it is not disallowed by the CLR) however it requires some IL weaving, which Jon Skeet demonstrated in his Unconstrained Melody project . 它在理论上是可行的(CLR不允许这样做),但是它需要进行IL编织,乔恩·斯凯特(Jon Skeet)在其“无约束旋律”项目中对此进行了证明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM