如何在不使用扩展名的情况下调用扩展方法 [英] How to call an extension method without using

查看:48
本文介绍了如何在不使用扩展名的情况下调用扩展方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

using System;

class Runner
{
    static void Main()
    {
        A a = new A();
        // how to say a.PrintStuff() without a 'using'
        Console.Read();
    }
}

class A { }

namespace ExtensionMethod
{
    static class AExtensions
    {
        public static void PrintStuff(this A a)
        {
            Console.WriteLine("text");
        }
    }
}

如何在不使用使用"的情况下调用扩展方法?而不是ExtensionMethod.AExtensions.PrintStuff(a),因为它没有使用扩展方法.

How would I call the extension method without a 'using'? And not ExtensionMethod.AExtensions.PrintStuff(a), since that doesn't make use of extension method.

推荐答案

可以像这样直接调用您的扩展,因为它只是一个静态方法,传递实例将作为第一个 this 参数:

It is possible to directly call your extension like so since it is simply a static method, passing the instance it will act on as the first this parameter:

A a = new A();
ExtensionMethod.AExtensions.PrintStuff(a);

如果您对更常用的扩展方法遵循此模式,这可能会使在此代码中发生的其他开发人员感到困惑.这还会使链接扩展调用(例如LINQ)看起来更像一种功能语言,因为您将嵌套每个调用而不是链接它们.

This might be confusing to other developers who happen across this code if you followed this pattern for more commonly used extension methods. It would also make chaining extension calls such as LINQ appear more like a functional language because you would be nesting each call instead of chaining them.

这篇关于如何在不使用扩展名的情况下调用扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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