c# - 类型不可知类在泛型类中调用泛型和非泛型方法?

标签 c# asp.net generics

我有以下类(class):

public class GenericClass<T> : IGenericClass<T> where T : class
{
    public GenericClass()

    public GenericClass(Entity e)

    public IQueryable<T> GenericMethod1()

    public IEnumerable<T> GenericMethod2()

    public T NonGenericMethod1(T t)
}

这门课效果很好;然而我开始遇到问题,我必须为我想要使用的每个类型 T 实例化 GenericClass 的另一个实例,这有点疯狂。我可以创建某种抽象来简化这个过程吗?

我正朝这个方向前进,但我不知道这是否是正确的选择,或者是否有更好的设计模式我可以使用;另外,这两个调用根本无法正常工作。

public class TestClass
{
    private Type type;

    public object Invoke(string method, object obj)
    {
        type = obj.GetType();

        MethodInfo m = typeof(GenericClass<>).GetMethod(method);

        var result = new object();

        if(m.IsGenericMethod == true)
            result = m.MakeGenericMethod(type).Invoke(null, new object[] { obj });
        else
            result = m.Invoke(null, new object[] { obj });

        return result;
    }
}

TIA

最佳答案

however I'm starting to run into issues where I have to instantiate another instance of GenericClass for every type T I want to use, and it's getting a little crazy

如果没有 GenericClass 的某些实现,很难猜测...但我看到构造函数和方法 - 没有属性(也没有字段?)。

如果是这种情况,您可能希望将 GenericClass 设为具有静态方法的静态类。那么你就不能实例化它,你可以直接从类型调用方法:

public static class GenericClass
{
  public static IQueryable<T> GenericMethod1<T>() where T:class

  public static IEnumerable<T> GenericMethod2<T>() where T:class

  public static object NonGenericMethod1(object t)
}

调用者

IQueryable<Customer> query = GenericClass.GenericMethod1<Customer>();
IEnumerable<Customer> items = GenericClass.GenericMethod2<Customer>();
Customer c = (Customer) GenericClass.NonGenericMethod1(customerInstance);

或者也许有属性或字段,但它们不依赖于 T,那么您可以将通用责任转移到方法而不是类。

现在您可以拥有一个实例,并且该实例可以处理您想要扔给它的所有 T。

public class GenericClass : IGenericClass
{
  public IQueryable<T> GenericMethod1<T>() where T:class

  public IEnumerable<T> GenericMethod2<T>() where T:class

  public object NonGenericMethod1(object t)
}

我对此答案的通用性表示歉意,但这是由于问题的通用性造成的。

关于c# - 类型不可知类在泛型类中调用泛型和非泛型方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6132036/

相关文章:

c# - 在 ASP.NET Web API 中序列化继承的类型

c# - Crystal Reports - 将提供程序从 OLEDBSQL 更改为 MSOLEDBSQL 以通过代码支持 TLS 1.2

c# - Debug.WriteLine 重载似乎有冲突

c# - 尽管已声明 !IsPostBack 已声明,但分数整数卡住了

c# - 不可空类型的通用约束

generics - 如何访问在 F# 中声明为泛型参数的类型的静态成员

c# - C#-BASS.Net一次创建一个频谱图(不播放音乐文件)

c# - 我可以在不绑定(bind)的情况下使用 DetailsView 控件吗?

html - 我如何在 Bootstrap 中垂直和水平居中 asp 按钮

C#泛型方法和动态类型问题