【问题标题】:How to define extension methods for generic class?如何定义泛型类的扩展方法?
【发布时间】:2011-04-14 13:04:36
【问题描述】:

我有一个通用接口:

public IRepository< T >
{

    void Add(T entity);

}

和一个类:

public class Repository< T >:IRepository< T >
{

    void Add(T entity)
    {      //Some Implementation
    }

}

现在我想做一个上述接口的扩展方法。我做了以下课程:

public static class RepositoryExtension

{

    public static void Add(this IRepository< T > dataAccessRepository, T entity, string additionalValue)

    {
        //Some Implementation
    }

}

但我在扩展 Add 方法中遇到错误。它无法识别我已传递给 IRepository 的类型“T”。我无法将此类型事件传递给我的扩展方法类,即 RepositoryExtension。请指导正确的方式。

【问题讨论】:

    标签: c# methods generics


    【解决方案1】:
    public static void Add<T>(this IRepository< T > dataAccessRepository, T entity, string additionalValue)
    

    试试看。 在添加之后立即注意&lt;T&gt;

    【讨论】:

    • 但在这种情况下,每当我调用此扩展方法时,我都会传递此类型。现在我这样做: IRepositoryemployeeRepository = new Repository (); employeeRepository.Add(entity);但是在您建议我将类型传递给扩展方法的情况下,也可以:employeeRepository(entity,"someValue");
    • 你试过了吗? C# 和 .Net 将根据 IRepository 的类型找出类型
    • 是的,我试过了,它奏效了。非常感谢 Rohith 的帮助。我做的完全一样,但在调用该方法时我也传递了类型。我没有通过 Type 'T' 就试过了,.Net 想通了:) 非常感谢
    【解决方案2】:
    IRepository<Employee> employeeRepository = new Repository<Employee>(); 
    employeeRepository.Add(entity);
    

    但如果你建议我将类型传递给扩展方法:

    employeeRepository<Employee>(entity,"someValue")
    

    http://just-dotnet.blogspot.in/2012/06/c-generics-introduction.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多