How to check assignability of types at runtime in C#?

后端 未结 6 1184
后悔当初
后悔当初 2021-02-06 02:11

The Type class has a method IsAssignableFrom() that almost works. Unfortunately it only returns true if the two types are the same or the first is in

6条回答
  •  礼貌的吻别
    2021-02-06 02:33

    Timwi's answer is really complete, but I feel there's an even simpler way that would get you the same semantics (check "real" assignability), without actually defining yourself what this is.

    You can just try the assignment in question and look for an InvalidCastException (I know it's obvious). This way you avoid the hassle of checking the three possible meanings of assignability as Timwi mentioned. Here's a sample using xUnit:

    [Fact]
    public void DecimalsShouldReallyBeAssignableFromInts()
    {
        var d = default(decimal);
        var i = default(i);
    
        Assert.Throws (int)d);
        Assert.DoesNotThrow( () => (decimal)i);
    }
    

提交回复
热议问题