如何将任何对象强制转换为实际类型

Lea*_*ner 1 .net c#

有没有办法object在运行时对一些特定类型进行类型转换?有可能吗?

public static void TryTypeCasting(object obj)
{
    Type type = obj.GetType();
    // Can I use this "type" variable somehow to typecast "obj" to its actual type?
}
Run Code Online (Sandbox Code Playgroud)

我正在使用C#4.0.


编辑1:

谢谢大家的投入.

我可能想要实现一些不可能的事情.但我发布了这个问题是为了获得专家的意见,并知道这样的事情是否可以在C#4.0中实现.

这是一个实时问题:

在我们的产品中,我们的客户端API(方法)序列化了Employee从我们的实体类派生的"some"类(例如)的实例Person.该序列化实例(即字符串值)通过一些中间类发送到服务器端API(一种负责将字符串反序列化为适当类的实例的方法).因此,在服务器端,只有API获取的是字符串.

但是,在序列化时,自定义序列化程序始终将类的完全限定名称(其实例正在序列化)添加为结果输出的第一行.所以在服务器端,在读取第一行时,我知道Employee字符串应该被反序列化的类(即在这种情况下).

此外,我们调用接受类型参数的Web服务方法(我不允许更改)Person.

现在,在此阶段反序列化后,我有一个Employee存储在类型变量中的实例object.但即使实例可用,我也无法将其作为参数传递,直到我将其强制转换为Employee.我怎样才能做到这一点?

示例代码在此处提供:

 public static void Deserialize(string serializedObject)
        {
            StringReader stringReader = new StringReader(serializedObject);

            // Read the first line to know class and assembly details
            string firstLine = stringReader.ReadLine();
            string[] assemblyAndClassDetails = firstLine.Split(new[] { ',' }, StringSplitOptions.None);
            string className = assemblyAndClassDetails[0];
            string assemblyName = assemblyAndClassDetails[1];

            // Remove the first line before passing it to the serializer
            serializedObject = serializedObject.Remove(0, firstLine.Length);

            // Know the type of the serialized instance
            Type typeToBeDeserializedTo = Type.GetType(className);

            DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeToBeDeserializedTo);
            using(MemoryStream memoryStream = new MemoryStream(Encoding.ASCII.GetBytes(serializedObject)))
            {
                memoryStream.Position = 0;
                object deserializedObject = dataContractJsonSerializer.ReadObject(memoryStream);

                // NOW I WANT TO call a method that accepts an argument of type `Person` How can I do this?
            }
        }
Run Code Online (Sandbox Code Playgroud)

Jon*_*Jon 6

不,这完全不可能(除非在编译时已知特定类型,在这种情况下,您可以例如硬编码演员).

它永远不会是任何其他方式,因为类型转换意味着编译器完全知道结果的类型是什么.编译器如何才能知道只能在运行时确定的内容?

无论什么时候出现这个问题(并且经常这样做),答案是"对于你的情况,可能有一个适当的解决方案,既不涉及这种假设类型的演员也不反映".如果您更详细地陈述您的案例,我们可以建议这样的解决方案.