【问题标题】:generic partial methods in C#?C# 中的通用部分方法?
【发布时间】:2021-10-15 20:38:23
【问题描述】:

Partial classes and Partial methods 状态:

部分方法可以是泛型的。约束放在定义的部分方法声明上,并且可以选择在实现的部分上重复。实现声明中的参数和类型参数名称不必与定义声明中的相同。

视觉上"Constraints are put on the defining partial method declaration, and may optionally be repeated on the implementing one.""Parameter and type parameter names do not have to be the same in the implementing declaration as in the defining one."的代码示例是什么?

我不知道上面 2 个语句在代码中的视觉效果如何。

【问题讨论】:

    标签: c# partial partial-methods


    【解决方案1】:

    声明

    包括通用约束:

    public void Method<TName>(int name) where T : class;
    

    实施

    没有重复的通用约束,以及不同的参数名称(但相同的签名):

    public void Method<TOther>(int other)
    {
        // ....
    }
    

    【讨论】:

      【解决方案2】:

      实现声明中的参数和类型参数名称不必与定义中的相同。

      public partial class C {
          public partial void M<T>(int x);
      }
      
      public partial class C {
          public partial void M<U>(int y) {
              // implementation goes here...
          }
      }
      

      M 的两个声明具有不同的类型参数名称(TU),以及不同的参数名称(xy)。

      约束放在定义的部分方法声明上,并且可以选择在实现的部分上重复。

      这是不正确的。 C# language specification 说:

      声明中对应的类型参数必须具有相同的约束(类型参数名称的模数差异)。

      请参阅我发布的GitHub issue

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-10-19
        • 2011-11-01
        • 1970-01-01
        • 2010-10-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-29
        相关资源
        最近更新 更多