我能做到这一点,而无需使用IF条件 [英] Can i do it without using IF condition

查看:104
本文介绍了我能做到这一点,而无需使用IF条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个虚拟类,即计划,TESTME&安培; 。测试

class Program : Test
{
    Test _test = null;
    TestMe _testMe = null;
    static void Main(string[] args)
    {

    }

    private void Foo()
    {
                }

    private void Foo1()
    {
        if (_testMe != null)
        {
            _test.BarTest();
        }
    }

    private void Foo2()
    {
        if (_testMe != null)
        {
            _test.FooTest();
        }
    }
}

class Test
{
    public void FooTest()
    {
        //Do some coding
    }

    public void BarTest()
    {
        //Do some coding
    }
}

作为,你可以看到我的程序类是继承我的其他类的测试,然后在我的课的程序我有一个名为函数的 Foo1 这是调用的测试类的函数,如果的 _testMe! = NULL 。由于,只有两个功能在我班上的程序,所以我已经申请 if条件,但假设我已经一个内置的类在里面定义的函数100。我会很难,我到处适用的条件。所以,我的简单的问题是,我不得不做出这样的条件让自己的定义函数的其余部分将不会调用从类的测试的方法。我硝基甲苯要到处适用的条件,只是我想是定义一个条件,将每一个案件工作。我能做到吗?

As, you can see my Program class is inheriting my other class Test, and in my class Program i have a function named Foo1 which is calling the Test class function if the of _testMe != null. As, there are only two functions in my class Program, so i have applied if condition, but suppose i have already a built in class with 100 of function defined in it. I would be hard for me to apply conditions everywhere. So, my simple question is, i have to make such a condition so that my rest of the defined function will not call any method from the class Test. I dnt want to apply conditions everywhere, just i want is to define one condition that will work for every case. Can i do it?

推荐答案

这个扩展方法是什么?

    public static void Call<T>(this T obj, Action<T> method) where T : class
    {
        if ( obj != null )
            method( obj );
    }

    public static TResult Call<T, TResult>(this T obj, Func<T, TResult> method) where T : class
    {
        return obj == null? default( TResult ) : method(obj);
    }

这篇关于我能做到这一点,而无需使用IF条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆