C# 具有默认构造函数的泛型对象列表
我有一个简单的泛型类,它应该接受T并创建一个属性。如果我试图获取这个属性,但它不存在,它应该创建这个T类型的新实例并返回它。这就是为什么我需要在T上设置new()约束C# 具有默认构造函数的泛型对象列表,c#,list,generics,constraints,C#,List,Generics,Constraints,我有一个简单的泛型类,它应该接受T并创建一个属性。如果我试图获取这个属性,但它不存在,它应该创建这个T类型的新实例并返回它。这就是为什么我需要在T上设置new()约束 public class ExternalRepository<T> where T : class, IRepositoryable, new() { public IRepositoryable Value { get { if (Reques
public class ExternalRepository<T> where T : class, IRepositoryable, new()
{
public IRepositoryable Value
{
get
{
if (RequestCacheManager.GetAt<T>(typeof(T).Name) == null)
RequestCacheManager.SetAt<T>(typeof(T).Name, new T());
return RequestCacheManager.GetAt<T>(typeof(T).Name);
}
}
}
公共类外部存储库,其中T:class,IRepositoryable,new()
{
公共可接受值
{
得到
{
if(RequestCacheManager.GetAt(typeof(T).Name)==null)
SetAt(typeof(T).Name,new T());
return RequestCacheManager.GetAt(typeof(T).Name);
}
}
}
现在我需要创建一个列表。但由于新的()约束,这看起来是不可能的。我需要这样的东西:
public static List<ExternalRepository<T>> ExternalRepositories { get; set; } where T : class, IRepositoryable, new()
publicstaticlist ExternalRepositories{get;set;}其中T:class,IRepositoryable,new()
但这是无效的。你能帮我解决这个问题吗
谢谢。您想把
ExternalRepository
和ExternalRepository
放在一个列表中,对吗
遗憾的是,这不能明确地做到。您必须使用接口或基类
public interface IExternalRepository
{
// declaration of common properties and methods
}
public class ExternalRepository<T> : IExternalRepository
where T : class, IRepositoryable, new()
{
// implementation of common properties and methods
// own properties and methods
}
public static List<IExternalRepository> ExternalRepositories { get; set; }
公共接口IExternalRepository
{
//公共属性和方法的声明
}
公共类外部存储库:IExternalRepository
其中T:class,IRepositoryable,new()
{
//通用属性和方法的实现
//自己的属性和方法
}
公共静态列表外部存储库{get;set;}
或
公共类外部存储库
{
//共享属性和方法
}
公共类ExternalRepository:ExternalRepository
其中T:class,IRepositoryable,new()
{
//自己的属性和方法
}
公共静态列表外部存储库{get;set;}
另请参见我对问题的答复。您无法创建泛型属性,因此无法为其设置约束?尝试使用
method
而不是property
像publicstaticlist ExternalRepositories(),其中T:class,irepositionable,new()
我需要创建属性。方法很好,但它只是将这个问题移到了一个方法中。因此,在这种情况下,您可以创建包含此属性的泛型类并为其设置约束。是的,我也尝试了List,但这会引发错误,因为T类型必须具有隐式构造函数。这就是为什么我需要在列表上设置约束。错误是:“ServiceModel.Interface.IRepositoryable”必须是具有公共无参数构造函数的非抽象类型,才能在泛型类型或方法“SSO2.Managers.ExternalRepository”中将其用作参数“T”。太好了,谢谢。我很长一段时间都在试图解决这个问题,但我完全忽略了这个解决方案。现在看起来很明显:-)
public class ExternalRepository
{
// shared properties and methods
}
public class ExternalRepository<T> : ExternalRepository
where T : class, IRepositoryable, new()
{
// own properties and methods
}
public static List<ExternalRepository> ExternalRepositories { get; set; }