Streamlined way to do C# run-time type identificat

2019-05-26 09:36发布

问题:

I find myself using a common run-time type identification pattern, especially when writing code that handles controls of varying types. Here is the pattern:

if (ctrl is ControlTypeEtc)
    (ctrl as ControlTypeEtc).SomeMethod();

I do this to avoid having to do a NULL check in case the as operator returns NULL. Is there a way to streamline this to a single operation?

回答1:

No way to do this in a single operation.

However, using as and checking for null is cheaper as there is only one case instead of two as in your code sample.



回答2:

I would write it as:

ControlTypeEtc ctrl2 = ctrl as ControlTypeEtc;
if (ctrl2 != null)
    ctrl2.SomeMethod();

That avoids the double check (which may be optimized into one but I'm not sure).

Another way:

try
{
    ControlTypeEtc ctrl2 = (ControlTypeEtc)ctrl;
    ctrl2.SomeMethod();
}
catch (InvalidCastException e)
{
}


回答3:

Bottom line is, "Big picture" you should know if your instance is null before you proceed coding against it. there really is no reason to find a shortcut around that step.

That said, if you are using C# 3 or better you have Extensions methods which can be used to "hide" this detail from the main logic of your code. See below the sample with 'SomeType' and 'SomeMethod' and then an extension method called 'SomeMethodSafe'. You can call 'SomeMethodSafe' on a Null reference without error.

Don't try this at home.

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            SomeType s = null;
            //s = new SomeType();
            // uncomment me to try it with an instance

            s.SomeMethodSafe();

            Console.WriteLine("Done");
            Console.ReadLine();
        }
    }

    public class SomeType
    {
        public void SomeMethod()
        {
            Console.WriteLine("Success!");
        }
    }

    public static class SampleExtensions
    {
        public static void SomeMethodSafe(this SomeType t)
        {
            if (t != null)
            {
                t.SomeMethod();
            }
        }
    }
}


标签: c# null rtti