【问题标题】:Can someone explain me that syntax: QueryService<T>(this IServiceProvider serviceProvider, out T service) where T : class [closed]有人可以解释一下语法吗:QueryService<T>(this IServiceProvider serviceProvider, out T service) where T : class [关闭]
【发布时间】:2019-07-12 12:28:56
【问题描述】:

我在一个 C# 项目(我不记得是哪一个)上看到了一段代码,看起来像这样:

public static class ComExt
{
    // ... blablabla ...

    static public void QueryService<T>(this IServiceProvider serviceProvider, out T service) where T : class
    {
        // ... blablabla ...
    }

    static public int QueryInterface(this object provider, ref Guid riid, ref IntPtr ppvObject)
    {
        // ... blablabla ...
    }

但在第一种方法中,我不懂语法。 尤其是QueryService&lt;T&gt;(this) where T : class

有人可以向我解释该方法中发生了什么吗? 也许还有其他使用该语法的示例?

谢谢:)

【问题讨论】:

标签: c# methods syntax


【解决方案1】:

你的问题的问题是标题是这样写的,可能没有人会搜索它,在这里回答可能不会带来任何分数:)。

正如在 cmets 中提到的,这些是扩展方法。这意味着它们可以扩展一些常规类的功能。 关于扩展方法的一些信息:

  1. 它们应该在静态类中声明;
  2. 扩展类应该是文件中的第一个类。 (在 C# 中,一个文件中可以有多个类,但扩展类只有在文件中的第一个类才有效);
  3. 扩展函数也应该是静态的,因为在扩展的关键字“this”后面有一个动态成员;
  4. 扩展函数的第一个参数应该以“this”关键字(如上所述)开头,因为它告诉编译器扩展了哪个对象。

在您的情况下:static public void QueryService&lt;T&gt;(this IServiceProvider serviceProvider, out T service) where T : class 意味着由于有了这个函数,任何 IServiceProvider 类型对象都将能够具有附加(扩展)函数 QueryService,它将采用应该是类(而不是结构)的泛型类型:where T : class .

out T service 表示传递的参数不能被初始化(因为out 尽管ref 不需要参数初始化)。

用法如下:

CustomServiceType myService; 
IServiceProvider serviceProvider = new TypeWhichImplementsIServiceProvider();
//Now we can use extension function
serviceProvider.QueryService<CustomServiceType>(out myService); 
//After this function myService should be initialized (probably...)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-24
    • 2013-03-31
    • 1970-01-01
    • 2011-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多