C# 函数参数中 this的作用

来自公司的代码

		protected virtual void PlayEnterEffects(System.Action onEnterScreen)
		{
    
    
			onEnterScreen.InvokeSafely();
		}
public static void InvokeSafely(this System.Action action)
        {
    
    
            if (action != null)
            {
    
    
                try
                {
    
    
                    action();
                }catch (System.Exception e)
                {
    
    
                    //Assert.Fail(1, "Exception thrown while invoking {0}. Stack trace:\n{1}\n=====End stack trace=====", action, e.ToString());
                }
            }
        }

刚看到的时候是懵的,为什么这个 System.Action可以调用 InvockSafely()呢,尝试一番,发现与 函数参数中 this 关键字有关。所以就查了一下

解释:
这里会有一个this关键字,做什么用?其实这就是扩展方法!这个扩展方法在静态类中声明,定义一个静态方法,其中第一个参数定义可它的扩展类型。InvokeSafely()方法扩展了System.Action类,因为它的第一个参数定义了System.Action类型,为了区分扩展方法和一般的静态方法,扩展方法还需要给第一个参数使用this关键字。

原文链接

猜你喜欢

转载自blog.csdn.net/weixin_44238530/article/details/121187593
今日推荐