简体   繁体   中英

Converting from one nullable type to another nullable type

How can one convert from a nullable instance of class A to nullable instance of class B, while B is subclass of A, I tried this but it crashes:

class A
{
}

class B:A
{
}

A? instance_1=something_maybe_null;

if (instance_1.GetType() == typeof(B))
{
    ((B)(instance_1))?.some_method_in_B(paramters);
}

And if I move ? into parathesis, it doesn't compile:

...
if (instance_1.GetType() == typeof(B))
{
    ((B)(instance_1)?).some_method_in_B(paramters);
}

I am assuming this is a typo A? instance_1=something_maybe_null; A? instance_1=something_maybe_null; because you cannot do nullable reference types (ie classes), at least in C# 6.

If I understand your intent correctly, you just want to conditionally call a method in B if the object is actually an instance of B . If so, then you can do this:

class A
{
}

class B : A
{
    public void SomeMethodInB() {  }
}

A instance_a = something_maybe_null;
B instance_b = instance_a as B;
instance_b?.SomeMethodInB();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM