C# 使用类型为M<;的泛型参数定义方法;T>;在C中#
我正在为如何做到这一点而挣扎: 我试图让DoSomething方法接受从GenericClassC# 使用类型为M<;的泛型参数定义方法;T>;在C中#,c#,generics,C#,Generics,我正在为如何做到这一点而挣扎: 我试图让DoSomething方法接受从GenericClass派生的所有类,而不必将genericDerivated类分解为 class Program { static void Main(string[] args) { SomeClass.DoSomething<GenericDerived>(new GenericDerived()); //Still not compiler friendly } }
class Program
{
static void Main(string[] args)
{
SomeClass.DoSomething<GenericDerived>(new GenericDerived()); //Still not compiler friendly
}
}
class Base { }
class GenericClass<T> where T : Base { }
class GenericDerived : GenericClass<Base> { }
class SomeClass
{
public static void DoSomething<M, B>(M instance)
where B : Base
where M : GenericClass<B>
{
// Do something...
}
}
类程序
{
静态void Main(字符串[]参数)
{
SomeClass.DoSomething(new generic派生());//仍然不支持编译器
}
}
类基{}
类GenericClass,其中T:Base{}
类Generic派生:GenericClass{}
上课
{
公共静态无效剂量测量(M实例)
B:基地在哪里
其中M:GenericClass
{
//做点什么。。。
}
}
示例中没有名为t的类型参数。您还需要添加它及其约束
class SomeClass
{
public void DoSomething<M,T>(M instance) where T : Base
where M : GenericClass<T>
{
// Do something...
}
}
class-SomeClass
{
公共void DoSomething(M实例),其中T:Base
其中M:GenericClass
{
//做点什么。。。
}
}
示例中没有名为t的类型参数。您还需要添加它及其约束
class SomeClass
{
public void DoSomething<M,T>(M instance) where T : Base
where M : GenericClass<T>
{
// Do something...
}
}
class-SomeClass
{
公共void DoSomething(M实例),其中T:Base
其中M:GenericClass
{
//做点什么。。。
}
}
CLR,所以你不能用其他,已经参数化的类型参数化一个类型,如果这是你要问的…CLR,所以你不能用其他,已经参数化的类型参数化一个类型,如果这是你要问的…谢谢-我不知道为什么我错过了…感觉很愚蠢..哈哈。我会接受你的回答,如果有几个minutes@Nims我们所有人都会遇到这种情况:)@Nims-您需要在调用站点提供两个通用参数,即SomeClass.DoSomething(new-GenericDerived())
@Lee谢谢-但是没有办法在调用该方法时不必拆下该方法的类就可以以某种方式传入类型M并确保(M:GenericClass和T:Base)?@Nims-没有办法部分指定泛型类型参数,如果编译器无法推断它们,则必须全部提供它们。您可以将类型T
移动到封闭类,然后执行SomeClass.DoSomething(new-GenericDerived())代码>谢谢-我不知道为什么我错过了…感觉很愚蠢..哈哈。我会接受你的回答,如果有几个minutes@Nims我们所有人都会遇到这种情况:)@Nims-您需要在调用站点提供两个通用参数,即SomeClass.DoSomething(new-GenericDerived())
@Lee谢谢-但是没有办法在调用该方法时不必拆下该方法的类就可以以某种方式传入类型M并确保(M:GenericClass和T:Base)?@Nims-没有办法部分指定泛型类型参数,如果编译器无法推断它们,则必须全部提供它们。您可以将类型T
移动到封闭类,然后执行SomeClass.DoSomething(new-GenericDerived())代码>