如何通过类型名称转换Object并将其作为参数传递给另一个方法

时间:2017-07-21 20:28:01

标签: c# reflection parameter-passing

这是我的代码:

using System.Reflection;
Public class ClassA
{
    public ClassA()
    {
        ClassB classB = new ClassB();
        classB.UsingType = "ClassD";
        ClassB.Do();
    }
}
Public class ClassB
{
    public string UsingType { get; set; }
    public void Do()
    {
        ClassC classC = new ClassC();
        Type type = Type.GetType(UsingType);
        Object obj = Activator.CreateInstance(type);
        classC.Do(obj); // Error : cannot convert from 'object' to 'ClassD'
    }
}
public class ClassC
{
    public void Do(ClassD classD) // If I change "ClassD" to "Object" It works!!
    {
        //Do something with classD
    }
}

我收到此错误:"无法转换为' object'到' ClassD'。"

如果我改变"做"方法参数" ClassC"来自" ClassD"到"对象"错误消失然后我可以把它投射到" ClassD"并使用该参数。但那不是我想要的。

有没有办法施展" obj" by" UsingType"字符串到" ClassD" (""" ClassB&#34的方法;)并消除编译时错误?

换句话说:(因为" ClassA"知道类型名称字符串并将其传递给" ClassB")我怎样才能从"对象"到#C; ClassC"的类型请问?

1 个答案:

答案 0 :(得分:0)

由于您确定ClassC的类型为ClassC obj = (ClassC)Activator.CreateInstance(type); classC.Do(obj); ,因此只需将其转换为预期类型即可。

Object

进一步说明这一点:ToString()是一种泛型类型,并且只有全局可用的属性/方法(例如GetHashCode()null。)

将其强制转换为类意味着编译器会尝试转换它,如果转换失败则返回public static String rfc5987_encode(final String s) throws UnsupportedEncodingException { final byte[] s_bytes = s.getBytes("UTF-8"); final int len = s_bytes.length; final StringBuilder sb = new StringBuilder(len << 1); final char[] digits = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; final byte[] attr_char = {'!','#','$','&','+','-','.','0','1','2','3','4','5','6','7','8','9', 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','^','_','`', 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','|', '~'}; for (int i = 0; i < len; ++i) { final byte b = s_bytes[i]; if (Arrays.binarySearch(attr_char, b) >= 0) sb.append((char) b); else { sb.append('%'); sb.append(digits[0x0f & (b >>> 4)]); sb.append(digits[b & 0x0f]); } } return sb.toString(); }