有没有办法在运行时将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?
}
我正在使用C#4.0。
编辑1:
感谢大家的投入。
我可能正试图实现一些不可能的事情。但是我发布了这个问题是为了获得专家对此的看法,并知道这样的事情是否可以在C#4.0中实现。
这是一个实时问题:
在我们的产品中,我们的客户端API(方法)序列化了从我们的名为Employee
的实体类派生的“some”类(例如Person
)的实例。该序列化实例(即字符串值)通过一些中间类发送到服务器端API(一种负责将字符串反序列化为适当类的实例的方法)。因此,在服务器端,只有API获取的是字符串。
但是,在序列化时,自定义序列化程序始终将类的完全限定名称(其实例正在序列化)添加为结果输出的第一行。所以在服务器端,在读取第一行时,我知道应该对字符串进行反序列化的类(即本例中为Employee
)。
此外,我们调用了一个接受Person
类型参数的Web服务方法(我不允许更改)。
现在,在此阶段反序列化后,我将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?
}
}
答案 0 :(得分:6)
不,这完全不可能(除非编译时知道特定类型,在这种情况下你可以例如硬编码演员)。
它永远不会是任何其他方式,因为类型转换意味着编译器完全知道结果的类型是什么。如何让编译器知道只能在运行时确定的东西?
每当这个问题出现时(并且经常发生),答案就是“对于你的情况,可能有一个适当的解决方案,既不涉及这种假设的演员也不反思”。如果您更详细地陈述您的案例,我们可以建议这样的解决方案。
答案 1 :(得分:4)
您无法在运行时执行此操作,因为您不知道对象的实际类型。此信息仅在运行时知道,而不是在编译时知道。
答案 2 :(得分:1)
假设您可以将对象分配给正确类型的变量(我不确定是否可能),您仍然无法在方法中编写任何代码,因为编译器不会知道类型是什么编译时间。
有几种选择:
答案 3 :(得分:1)
正如其他人所说,这是不可能的。
但是duck typing呢?
((dynamic)yourObject).SomeMethod();
类型检查会延迟执行代码。
请注意,应谨慎使用像C#这样的强类型语言的鸭子类型以及特定的一组用例。 不要在任何地方使用 dynamic
关键字替换强类型!