Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/265.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# ";是";及;作为「;C语言中的运算符#_C#_Type Conversion - Fatal编程技术网

C# ";是";及;作为「;C语言中的运算符#

C# ";是";及;作为「;C语言中的运算符#,c#,type-conversion,C#,Type Conversion,如果C中的as运算符只能用于引用和可为空的类型,那么对于is运算符?是否同样有效。is操作可用于任何类型,因为您始终可以检查任何类型的类型相等性。它在语义上与 if(someVariable.GetType().IsAssignableFrom(anotherVariable.GetType())) 您可以查看有关此的文档 它可以用于任何类型,因为“is”考虑装箱/拆箱 int test = 4; object test2 = test; bool isTrue = (test2 is int

如果C中的
as
运算符只能用于引用和可为空的类型,那么对于
is
运算符?

是否同样有效。
is
操作可用于任何类型,因为您始终可以检查任何类型的类型相等性。它在语义上与

if(someVariable.GetType().IsAssignableFrom(anotherVariable.GetType()))

您可以查看有关此的文档

它可以用于任何类型,因为“is”考虑装箱/拆箱

int test = 4;
object test2 = test;
bool isTrue = (test2 is int);

当您考虑如何实现“as”时,它会变得更加清晰。如果“as”是一个函数:

public T as<T>(object obj){
    if(obj is T)
    {
        return (T) obj;
    }
    else
    {
        return null;
    }
}
publictas(objectobj){
if(obj是T)
{
返回(T)obj;
}
其他的
{
返回null;
}
}
如图所示,T必须是可为null的类型或引用类型,否则将无法返回null

“is”运算符不会遇到此问题,因为它返回布尔值,因此不必担心目标是否可以表示为null。

if(someVariable.GetType()==anotherVariable.GetType())
不同,
is
如果类型是值类型的基类型,也会返回true。如果
someVariable
null
,它也不会抛出NullReferenceException。对于可空类型,也有一些细微的区别。