![](/img/trans.png)
[英]How do I correctly constrain to related class type when using a generic method?
[英]How do you constrain a generic type to be a class and support new()?
我正在尝试为 Cosmos DB Gremlin Graph API 数据源实现 GenericRepository 模式。 所以我有:
TEntity
,其中TEntity
是class
。 我也这样做了。错误类型“typename”必须是具有公共无参数构造函数的非抽象类型,以便将其用作泛型类型或方法“generic”中的参数“parameter”
在定义泛型类型时,您可以应用多个泛型约束,如下所示:
public class GenericRepository<TEntity> : IGenericRespository<TEntity>
where TEntity : class, new() //the new() constraint must come last
这些约束意味着,为了使类型与GenericRespository<>
一起使用,它必须既是 class(引用类型) ,又必须提供公共无参数构造函数。 (见文档)
在实践中,这意味着你可以有一个GenericRepository<object>
,但不是GenericRepository<int>
因为 int 是一个值类型,或者GenericRepository<Uri>
因为虽然Uri
是一个 class,但它没有一个 public parameter-less构造函数。
public class GenericRespository<T>
where T : class, new()
{
public T Create() => new T();
}
public class Repositories
{
//won't compile, int is a value type;
readonly GenericRespository<int> intRepository = new GenericRespository<int>();
//wont compile, Uri is a class, but no public
//parameterless constructor
readonly GenericRespository<Uri> uriRpository = new GenericRespository<Uri>(); //no public parameterless constructor, doesn't work.
//object is a class and supports new object(), so this works
readonly GenericRespository<object> objectRepository = new GenericRespository<object>(); //works fine
}
这些类型约束意味着您的GenericRespository<TEntity>
将能够自行创建新的TEntity
实例。 这样做的真正价值在于,您将能够创建自己的类并创建它们的存储库,而无需编写任何额外的代码。
正确答案是 Generics 可以有多个子句。 所以我能够简单地通过扩展子句 ( , new()
) 来解决我的问题。 现在TEntity
必须是class
和new()
这对我有好处!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.