does GetType() guarantee casting?

时间:2019-03-17 22:25:15

标签: c#

if o.GetType() == sometype is it guaranteed that o can be casted to sometype ?

that is if:

void f<T>(T o1, object o2) {
   if (o1.GetType() != o2.GetType()) return;
   T t = o2 as T;
   // can I assert that t is not null ??
}

3 个答案:

答案 0 :(得分:1)

是的,可以,但是我建议再进一步一步:

void f<T, U>(T t, U u) where T : class
{
    if (!t.GetType().IsAssignableFrom(u.GetType())) return;
    T ut = u as T;
    // can I assert that t is not null ?? Yes, you can
}

IsAssignableFrom应该将其固定为任何类型。

答案 1 :(得分:1)

为什么不只使用is运算符 1 ,尽管“也许”会慢一点

if (o2 is SomeType result) o1 = result;

或作为方法

private void SomeThingWeird<T>(ref T o1, object o2)
{
   if (o2 is T result)
      o1 = result;
}

参考

1 Drilling into .NET Runtime microbenchmarks: ‘typeof’ optimizations

答案 2 :(得分:-1)

为什么不做:

void f<T>(T o1, T o2) {
   if (o1.GetType() != o2.GetType()) return;
   // can I assert that t is not null ??
}

对于我了解的内容,请检查if (o1.GetType() != o2.GetType()) return;以确保o2的类型为T,而不是派生类型。因此,o2的类型必须为T,并且转换时没有任何问题。