简体   繁体   English

如何将对象类型更改为其实际类型?

[英]how to change an object type to its actual type?

I have an object which is actually string/integer.我有一个实际上是字符串/整数的对象。 I can get its type by obj.GetType().我可以通过 obj.GetType() 获取它的类型。 In the runtime I know it is a string.在运行时我知道它是一个字符串。 The problem is a function only accepts string or integer.问题是函数只接受字符串或整数。 If I wrote如果我写

int cnt = 0;
public object why()
{
    cnt++;
    if (cnt % 2 == 0) return 0;
    return "";
}
void A(int input) {
}
void A(string input) {
}
void Test()
{
    object obj = why();
    MethodInfo method = obj.GetType().GetMethod(nameof(A), new[] { obj.GetType() });
    //Need to call A by obj, but it threw an error :)
    method.Invoke(null, new[] { obj });
}

It returns error as it rejects object.它在拒绝对象时返回错误。 It could work if它可以工作,如果

func((string)obj)

But I need also cater integer ( and possibly other type too later, thus it may not appropriate to apply conditional statement for the scenario)但我还需要满足整数(可能还有其他类型太晚了,因此可能不适合对场景应用条件语句)

the optimum way is changing the type of the object before assign it to the function, but I am not sure if it is possible, which is string in the example func((string)obj).最佳的方法是改变对象的类型,将其分配给函数之前,但我不知道这是否是可能的,这是字符串中的例子FUNC((字符串)目标文件)。

You can use reflection to get the correct method based on the type of the object.您可以使用反射根据对象的类型来获取正确的方法。 Then you can use Invoke() to actually call the method with the argument.然后您可以使用Invoke()实际调用带有参数的方法。

object obj = why();
MethodInfo method = typeof(YourClass).GetMethod(nameof(YourClass.A), new [] { obj.GetType() } );
method.Invoke(maybe_an_object_here, new [] { obj } );
  • The class YourClass is the class which contains the method A .YourClass是包含方法A的类。
  • maybe_an_object_here is the object instance of YourClass on which you want to call the A method on. maybe_an_object_here是您要在其上调用A方法的YourClass的对象实例。 Depending on what you are doing this argument can be this (if it is an object of YourClass ).根据您在做什么,这个参数可以是this (如果它是YourClass的对象)。 In case it is a static method (it is not according to your code provided) you do not provide an object of that class but instead use the value null since you don't need objects to call static methods.如果它是一个static方法(它不是根据您提供的代码),您不提供该类的对象,而是使用值null因为您不需要对象来调用static方法。

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

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