gpt4 book ai didi

c# - 如何将任何对象类型转换为实际类型

转载 作者:太空宇宙 更新时间:2023-11-03 17:26:08 25 4
gpt4 key购买 nike

有没有办法在运行时将对象类型转换为某种特定类型?有可能吗?

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

我正在使用 C# 4.0。


编辑 1:

感谢大家的投入。

我可能正在尝试实现不可能的事情。但我发布这个问题是为了获得专家对此的看法,并了解在 C# 4.0 中是否可以实现这样的事情。

这是一个实时问题:

在我们的产品中,我们的客户端 API(方法)序列化派生自名为 Person 的实体类的“某些”类(例如 Employee)的实例。该序列化实例(即字符串值)通过一些中间类发送到服务器端 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?
}
}

最佳答案

不,这完全不可能(当然除非特定类型在编译时已知,在这种情况下您可以对强制转换进行硬编码)。

不可能是任何其他方式,因为类型转换意味着编译器完全了解结果的类型。编译器怎么可能知道只能在运行时确定的东西?

每当这个问题出现时(它经常出现),答案是“可能有一个适合您的情况的解决方案,既不涉及这种假设类型的转换也不涉及反射(reflection)”。如果您更详细地陈述您的情况,我们可以建议这样的解决方案。

关于c# - 如何将任何对象类型转换为实际类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12934689/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com