![](/img/trans.png)
[英]How can I cast a variable with the `object` type to class with generic type in c#?
[英]C# how to check if a variable of type object can be cast to a struct type?
在 C# 中,如果我有一个类型为object
的变量,我如何检查是否可以将其转换为值类型的类型T
? as
运算符不起作用,因为 T 是值类型,并且o.GetType().Equals(typeof(T))
只检查 object 是否是 T 类型的装箱变量,但不是投给T。
尝试这个
object obj = "wer";
var isCompatible = typeof(T).IsAssignableFrom(obj.GetType());
你可以试试这些:
object obj = "wer";
typeof(T).IsInstanceOfType(obj)
阅读更多: https://docs.microsoft.com/en-us/dotnet/api/system.type.isinstanceoftype?view=netcore-3.1
或者
object obj = "wer";
obj is T;
阅读更多: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/is
或者
object obj = "wer";
typeof(T).IsAssignableFrom(obj.GetType())
阅读更多: https://docs.microsoft.com/en-us/dotnet/api/system.type.isassignablefrom?view=netcore-3.1
但是,您需要注意IsAssignableFrom
和IsInstanceOfType
和is
之间的区别。 在这里阅读更多:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.