继承泛型类型

问题描述 投票:-2回答:1

假设

  1. 我已经知道框架不允许在示例中讨论模式
  2. 我需要通过更简单的通用模式应用程序获益。

上下文

我正在审查客户端的代码,并确定了一些可在多个Classes / Structs中可靠实现的静态/实例方法。

我正在寻找一种类似于示例的方法,该方法将允许执行所描述的设计。

public class StaticObject<T>: T where T: class, new(){
    public void Method1(){}
    public int Method2(){}
}

public class Object : StaticObject<KeyedCollection<string, object>>{

}

Question

我可以利用什么替代方法来获得从Generic T继承并暴露两种静态方法的类的能力?

enter image description here

.net generics inheritance .net-4.6.1
1个回答
0
投票

好吧,也许你想要这样的东西。

using System;

public interface INeededForMethod1
{
    ...
}

public interface INeededForMethod2
{
    ...
}

public class GenericExtender<T>
{
    public T @Object { get; }
    private Func<T, INeededForMethod1> Method1Helper { get; }
    private Func<T, INeededForMethod2> Method2Helper { get; }

    public GenericExtender(
            Func<T> constructor,
            Func<T, INeededForMethod1> method1Helper,
            Func<T, INeededForMethod2> method2Helper)
   {
       this.Object = constructor();
       this.Method1Helper = method1Helper;
       this.Method2Helper = method2Helper;
   }

   public void Method1()
   {
       var method1Stuff = this.Method1Helper(this.@Object);
       ...
   }

   public void Method2()
   {
       var method2Stuff = this.Method2Helper(this.@Object);
       ...
   }        
}

细节是灵活的,如果您需要T的界面,您可以将其组合到GenericExtender<T>的实现中。

© www.soinside.com 2019 - 2024. All rights reserved.