How to do a static cast in C#?

后端 未结 4 2143
迷失自我
迷失自我 2020-12-21 08:43

Given a couple types like this:

interface I {}
class C : I {}

How can I do a static type cast? By this I mean: how can I change its type in

4条回答
  •  一整个雨季
    2020-12-21 09:14

    If you're really just looking for a way to see if an object implements a specific type, you should use as.

    I i = whatever as i;
    if (i == null) // It wasn't
    

    Otherwise, you just cast it. (There aren't really multiple types of casting in .NET like there are in C++ -- unless you get deeper than most people need to, but then it's more about WeakReference and such things.)

    I i = (I)c;
    

    If you're just looking for a convenient way to turn anything implementing I into an I, then you could use an extension method or something similar.

    public static I ToI(this I @this)
    {
        return @this;
    }
    

提交回复
热议问题