Streamlined way to do C# run-time type identification that avoids a NULL check?

微笑、不失礼 提交于 2019-12-12 09:56:45

问题


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();
            }
        }
    }
}


来源:https://stackoverflow.com/questions/14791514/streamlined-way-to-do-c-sharp-run-time-type-identification-that-avoids-a-null-ch

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!