2017-06-05 126 views
1

我在C#中使用泛型类型,我新使用泛型类型。所以,现在我陷入了一个问题。我有一些类这样的:泛型类型的声明方法

public class MyModel1 
{ 
} 

public class MyModel2 
{ 
} 

public class BaseClass<T> 
{ 
} 

public class ChildClass1 : BaseClass<MyModel1> 
{ 
} 

public class ChildClass2 : BaseClass<MyModel2> 
{ 
} 

public class AnotherClass 
{ 
    //What will be the syntax of declaring this method 
    //The syntax of the following method is wrong and incomplete. 
    //It's there just to give an idea about whai i want to do. 
    public void MyMethod<T>() 
     where T : BaseClass<..what to write..> 
    { 

    } 
} 

我的问题是什么将是宣布的MyMethod的语法是否正确,如果我想调用的MyMethod这样的:

MyMethod<ChildClass1>(); 
+3

你的意思'其中T:BaseClass的'?还有方法缺少返回类型或void。 – Nkosi

+0

编辑并添加返回类型。不,看起来像'T:BaseClass '不是我正在寻找的。 –

回答

0

如果我理解正确,您尝试过滤“MyMethod”,以便T是“ChildClass ...”类型的类。

可以通用的参数添加到您的函数是这样的:

public void MyMethod<T, U>() 
where T : BaseClass<U> 
{ 

} 

但你要调用的MyMethod以这种方式。

MyMethod<ChildClass1, MyModel1>(); 

所以使用起来相当复杂。


另一种解决方案是创建一个新的 “空白” 类:

public abstract class Base // mark it as abstract if you don't need to use it in your code 
{ 
} 

public class MyModel1 
{ 
} 

public class MyModel2 
{ 
} 

public class BaseClass<T> : Base //The class inherits the new class 
{ 
} 

public class ChildClass1 : BaseClass<MyModel1> 
{ 
} 

public class ChildClass2 : BaseClass<MyModel2> 
{ 
} 

public class AnotherClass 
{ 
    public void MyMethod<T>() 
    where T : Base 
    { 
    } 
} 
+0

谢谢。我也在考虑同样的事情(创建另一个基类)作为备份计划。我想我现在必须采取这种方式,直到我更好地掌握泛型并找到更好的解决方案(如果实际上有更好的解决方案)。 –

0

你忘了提回键入并在课程名称后面添加<T>。例如,如果返回类型为void,你可以声明的方法:

 public void MyMethod<T>() 
     where T : BaseClass<T> 
{ 

} 
+0

编辑并添加返回类型。不,看起来像'T:BaseClass '不是我正在寻找的。 –

0

这将工作(我指的是它编译)

public void MyMethod<T>() 
    where T : BaseClass<MyModel1> 
{ } 

那么,这是否:

public void MyMethod<T>() 
    where T : ChildClass1 
{ } 

阅读您的评论后

进一步编辑...

你可以这样做:

public class AnotherClass<TBaseClass, TModel> where TBaseClass : BaseClass<TModel> 
{ 
    public void MyMethod(TBaseClass input) 
    { } 
} 

我对这个术语,希望不进攻。我称之为疯狂的通用兔子洞。当我们试图将泛型和继承结合起来时,会发生什么情况,以便一组类可以完成一系列变得越来越混乱的目标,并且我们通过添加更多通用参数和更通用的类来解决它。

到达孔的底部,如果你
- 使用<dynamic>
- 检查,看看有什么实际的类型是使用GetType()typeof,或is
- 得到它的编译,但不记得是什么感觉应该这样做

+0

是的,他们工作。但是之后我需要为所有MyModels(第一种方式)或所有ChildClasses(第二种方式)编写MyMethod。这就是为什么我在寻找一些通用的东西 –