【问题标题】:Cast a variable to a Type and call Methods将变量转换为类型并调用方法
【发布时间】:2013-05-24 13:15:56
【问题描述】:

在将对象转换为类型后,我将如何调用对象的方法调用? 我有一个 KeyValuePair 存储对象的类型和对象本身。然后我想将此对象转换为其键类型并调用该类类型的方法。

    KeyValuePair<Type, Object> client = myClients.Find(
        delegate(KeyValuePair<Type, Object> result)
        {
            return (result.Key == myClients[clientNumber].Key); // Match client of the same type
        }
    );

    if (client.Value != null)
    {
        // cast client.Value to type of client.Key, then invoke someMethod 
        client.Key.GetType() v = Convert.ChangeType(client.Value, client.Key.GetType());
        return v.someMethod();
    }  

有什么办法吗?

谢谢。

【问题讨论】:

  • 你能不能不让对象用定义的方法实现接口然后简单地做return ((IMyInterface)client.Value).SomeMethod()

标签: c# reflection types casting keyvaluepair


【解决方案1】:

而不是

return v.someMethod();

你必须通过反射调用方法

var method = typeof(v).GetMethod("<methodName>",...);

return method.Invoke(v, new[]{<parameters of the method>});

请注意,method.Invoke() 将返回一个对象,因此您必须将其强制转换为所需的类型(如果需要)。

【讨论】:

  • 嗨,我添加了var x = (client.Key.GetType()).GetMethods();,但它返回了一个完整的方法列表:System.Reflection.MethodInfo[163] 其中没有一个是client.Key 类型的方法。我的对象也只有 4 种方法。有什么想法吗?
  • @Travv92 给你什么client.Key.GetType().Name
【解决方案2】:

最简单的方法是使用dynamic关键字:

dynamic v = client.Value;
v.SomeMethod();

【讨论】:

  • 当我使用它时,我得到:Error 8 One or more types required to compile a dynamic expression cannot be found. Are you missing a reference?。知道为什么吗?
  • @Travv92:您使用的是什么 .NET 框架?什么版本的VS?
  • @Travv92:另外,请参阅:stackoverflow.com/questions/11725514/…
【解决方案3】:

当您不批量执行某项操作时,最快的方法是使用 Type.InvokeMember 方法和正确的 BindingFlags

【讨论】:

    【解决方案4】:

    如果 v.someMethod() 中的 someMethod 相同,则您的键可以实现接口 - 因此您可以取消 Convert.ChangeType 逻辑。

    【讨论】:

      猜你喜欢
      • 2021-03-17
      • 1970-01-01
      • 2017-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-13
      • 2020-10-25
      • 2020-02-01
      相关资源
      最近更新 更多