2015-10-16 18 views
2

我有一个这样的接口:类型参数是相同其外类型

public interface IStuff 
{ 
    bool DoSomethingWith<T>(T type); 
} 

这类实现它

public class MyStuff<T> : IStuff 
    { 

     readonly ISomeClass<T> _cls; 

     public MyStuff(ISystemCache cache) 
     { 
      _cls= cache.Get<T>(); 
     } 

     public bool DoSomethingWith<T>(T type) 
     { 
      //dummy code here that returns a bool 
      Type theType = typeof(T); 
      return theType == typeof(T); 
     } 
    } 

现在的原因的类型T是在类MyStuff是因为我想让它在实现IStuff的类的构造函数中可用。 MyStuff将以某种类型传递以在其DoSomethingWith方法中使用。

现在DoSomethingWith也有一个类型T,因为我希望它可以在所有实现IStuff的类上使用。

IStuff将最多有一个或两个实现;目前只有一个,但是一旦我完成设计,就会增加另一个。但是会有大约5-6个不同的ISomeClass实现发送到MyStuff类。对于ISomeClass的每个实现,我不想重复MyStuff。后来MyStuff_V2会做别的事情会会英寸

发送的ISomeClass的实现如何去设计这个让我不明白的是编译器警告“类型参数T具有相同的名称从外部类MyStuff<T>类型参数?

编辑 这是一个很做作的例子,可能不是完美的,但目的是为了能够创建在接口方法的一个泛型类型,这也是提供给实现该接口的类的构造函数。

回答

1

你不得不做出IStuff通用:

public interface IStuff<T> 
{ 
    bool DoSomethingWith(T type); 
} 

变化MyStuff<T>实施IStuff<T>

public class MyStuff<T> : IStuff<T> 

,并与用户可于DoSomething执行删除通用参数:

public bool DoSomethingWith(T type) 
{ 
    //dummy code here that returns a bool 
    Type theType = typeof(T); 
    return theType == typeof(T); 
} 
+0

IStuff将至多一个或两个实现方式具有;目前只有一个,但是一旦我完成设计,就会增加另一个。但是大约有5-6个不同的ISomeClass实现被发送到MyStuff类。我不想为每个ISomeClass的实现重复MyStuff。随着MyStuff :IStuff 这是什么会发生的权利?后来MyStuff_V2会做一些其他的事情,将在 – user20358

+0

@ user20358发送ISomeClass的实现 - 所以最终目标是只有一个没有泛型'T'参数的'MyStuff'类?否则,你最终会以倍数结尾(例如:MyStuff '和MyStuff 等) – SwDevMan81

+0

现在我们只说一个实现,那么就是MyStuff,但是是的,它需要在MyStuff 以及MyStuff 。如果它只是一种类型,我可以用where子句限制它。但事实并非如此,我需要让它适用于目前尚未发现的多种类型。在MyStuff内部我将使用第三方框架,可以与传递给它们的任何类型一起使用。我的猜测是他们使用反射。 MyStuff的工作是将N个类型传递给这些第三方框架。 – user20358

1

你想让这两种类型有所不同吗?只需更改类型:

public bool DoSomethingWith<T2>(T2 type) 
{ 
    //dummy code here that returns a bool 
    Type theType = typeof(T2); 
    return theType == typeof(T); 
} 

否则,您必须执行@Marcin建议的操作。

更完整的示例:

void Main() 
{ 
    IStuff s = new MyStuff<int>(); 
    Console.WriteLine(s.DoSomethingWith(2.34)); // compare will be false (double != int) 
    Console.WriteLine(s.DoSomethingWith(5)); // compare will be true (int == int) 
} 

// Define other methods and classes here 
public interface IStuff 
{ 
    bool DoSomethingWith<T2>(T2 type); 
} 

public class MyStuff<T> : IStuff 
{ 
    public MyStuff() 
    { 
     // Do whatever with type T 
    } 

    public bool DoSomethingWith<T2>(T2 type) 
    { 
     // dummy code here that returns a bool 
     Type theType = typeof(T2); 
     return theType == typeof(T); 
    } 
} 
+0

他们将是一样的。 MyStuff的方法将以相同类型运行,通过构造函数 – user20358

+0

发送更新的问题 – user20358

相关问题