[英]C# how to check if a variable of type object can be cast to a struct type?
In C#, if I have a variable of type object
, how can I check if I can cast it to a type T
which is a value type?在 C# 中,如果我有一个类型为
object
的变量,我如何检查是否可以将其转换为值类型的类型T
? The as
operator doesn't work, since T is a value type, and o.GetType().Equals(typeof(T))
just checks if object is a boxed variable of type T, but not if it is something that can be cast to T. as
运算符不起作用,因为 T 是值类型,并且o.GetType().Equals(typeof(T))
只检查 object 是否是 T 类型的装箱变量,但不是投给T。
Try this尝试这个
object obj = "wer";
var isCompatible = typeof(T).IsAssignableFrom(obj.GetType());
You can try these:你可以试试这些:
object obj = "wer";
typeof(T).IsInstanceOfType(obj)
Read more: https://docs.microsoft.com/en-us/dotnet/api/system.type.isinstanceoftype?view=netcore-3.1阅读更多: https://docs.microsoft.com/en-us/dotnet/api/system.type.isinstanceoftype?view=netcore-3.1
Or或者
object obj = "wer";
obj is T;
Read more: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/is阅读更多: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/is
Or或者
object obj = "wer";
typeof(T).IsAssignableFrom(obj.GetType())
Read more: https://docs.microsoft.com/en-us/dotnet/api/system.type.isassignablefrom?view=netcore-3.1阅读更多: https://docs.microsoft.com/en-us/dotnet/api/system.type.isassignablefrom?view=netcore-3.1
However you need to note about the differences between IsAssignableFrom
and IsInstanceOfType
and is
.但是,您需要注意
IsAssignableFrom
和IsInstanceOfType
和is
之间的区别。 Read more here:在这里阅读更多:
https://stackoverflow.com/a/497001/1666800 https://stackoverflow.com/a/497001/1666800
https://stackoverflow.com/a/15853224/1666800 https://stackoverflow.com/a/15853224/1666800
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.