C# 具有泛型参数和抽象类的泛型
我有两个通用基类。第二个泛型类对其第一个类的参数具有约束C# 具有泛型参数和抽象类的泛型,c#,silverlight,generics,C#,Silverlight,Generics,我有两个通用基类。第二个泛型类对其第一个类的参数具有约束 abstract class FirstClass<T> {...} abstract class SecondClass<U> where U : FirstClass {...} 抽象类第一类{…} 抽象类第二类,其中U:FirstClass{…} 这不起作用,因为没有定义FirstClass。所以我需要这样做 abstract class FirstClass<T> {...} abstr
abstract class FirstClass<T> {...}
abstract class SecondClass<U> where U : FirstClass {...}
抽象类第一类{…}
抽象类第二类,其中U:FirstClass{…}
这不起作用,因为没有定义FirstClass。所以我需要这样做
abstract class FirstClass<T> {...}
abstract class SecondClass<U, T> where U : FirstClass<T> {...}
抽象类第一类{…}
抽象类第二类,其中U:FirstClass{…}
这很有效。然而,这使得实现这些抽象类变得丑陋
class SomeClass {...}
class MyFirstClass : FirstClass<SomeClass> {...}
class MySecondClass : SecondClass<MyFirstClass, SomeClass> {...}
class-SomeClass{…}
类MyFirstClass:FirstClass{…}
类MySecondClass:第二类{…}
这对我来说似乎是多余的,因为我两次指定了SomeClass。有没有一种方法可以这样声明:第一类的T自动成为第二类的U。我真正想要的是这个样子
class SomeClass {...}
class MyFirstClass : FirstClass<SomeClass> {...}
class MySecondClass : SecondClass<MyFirstClass> {...}
class-SomeClass{…}
类MyFirstClass:FirstClass{…}
类MySecondClass:第二类{…}
虽然我怀疑这个确切的场景是可能的,但有没有更清晰的方法来做我正在尝试做的事情
编辑
一些人建议制作IFirstClass界面。但我的定义更接近于此
class FirstClass<T>
{
public T MyObj { get; set; }
}
class SecondClass<U, T> where U : FirstClass<T>
{
U MyFirstClass { get; set; }
}
class头等舱
{
公共T MyObj{get;set;}
}
二等舱,其中U:一等舱
{
U MyFirstClass{get;set;}
}
使用接口,我无法从SecondClass访问MyFirstClass.MyObj。虽然我可以在IFirstClass上创建一个
对象T MyObj{get;set;}
,然后使用new
隐藏它,但如果我这样做,silverlight将适合绑定。根据我的经验,创建泛型类的非泛型接口是最容易的。它还解决了在不知道泛型类型的情况下需要强制转换到基类的问题
interface IFirstClass {...}
abstract class FirstClass<T> : IFirstClass {...}
abstract class SecondClass<T> where T : IFirstClass {...}
接口IFirstClass{…}
抽象类第一类:IFirstClass{…}
抽象类第二类,其中T:IFirstClass{…}
创建一个由FirstClass实现的接口。然后您可以将SecondClass约束到接口。如果您实际使用的是FirstClass的泛型类型参数(从您的编辑来看,听起来像是这样),那么不,很遗憾,您要查找的是不可能的。编译器不会区分相关的类型参数和不相关的类型参数。这实际上是一个已标记为与此问题重复的答案
可以声明一组具有特定Id类型的接口。这不是一个完美的解决方案,但简化了实体类的声明
public interface IIntPersistentEntityService<TPersistentEntity>
: IPersistentEntityService<TPersistentEntity, int>
where TPersistentEntity : IPersistentEntity<int>
{
}
public interface IStringPersistentEntityService<TPersistentEntity>
: IPersistentEntityService<TPersistentEntity, string>
where TPersistentEntity : IPersistentEntity<string>
{
}
如果没有匹配的Id类型,则会出现编译器错误。虽然我在问题中没有提到silverlight,但这是一个silverlight项目。我不确定这是否会限制解决方案。如果您尝试将WCF RIA服务的TypeOf封送为POCO类,则会限制解决方案,因为泛型不能作为WCF或WCF RIA服务公开(没有一些主要的解决方法)。您是否使用有关FirstClass的任何类型特定信息?如果没有,我在这些实例中倾向于使FirstClass与某些IGenericFirstClass接口匹配,然后将约束指定为IGenericFirstClass。它隐藏了U型依赖项。U
和T
是不同的类型吗?@Stefan-我编辑了代码以试图澄清请查看我的编辑。我没有遇到需要向基类施压的问题。这是我的想法,但如果我们没有希望,我们还有什么?@cadrell0:careers.stackoverflow.com;)不过,说真的,别忘了接受其中一个答案。这些几乎是你唯一的选择。
public class UserService : IIntPersistentEntityService<User>
{
public User Get(int id)
{
throw new NotImplementedException();
}
}