使用泛型的 C# 存储库
我有以下用于单元测试的存储库:
public class MyTestRepository<T>
{
private List<T> entities = new List<T>();
public IQueryable<T> Entities
{
get { return entities.AsQueryable(); }
}
public T New()
{
//return what here???
}
public void Create(T entity)
{
entities.Add(entity);
}
public void Delete(T entity)
{
entities.Remove(entity);
}
}
我在 New() 方法中返回什么?
我已经尝试过:
public T New()
{
return (T) new Object();
}
但是当我运行单元测试时,这给了我以下异常:
System.InvalidCastException: Unable to cast object of type 'System.Object' to type 'MyCustomDomainType'.
关于如何实现 New() 方法有任何想法吗?
I have the following repository that I use for unit testing:
public class MyTestRepository<T>
{
private List<T> entities = new List<T>();
public IQueryable<T> Entities
{
get { return entities.AsQueryable(); }
}
public T New()
{
//return what here???
}
public void Create(T entity)
{
entities.Add(entity);
}
public void Delete(T entity)
{
entities.Remove(entity);
}
}
What do I return in the New() method?
I have tried this:
public T New()
{
return (T) new Object();
}
But that gives me the following exception when I run my unit test:
System.InvalidCastException: Unable to cast object of type 'System.Object' to type 'MyCustomDomainType'.
Any idea on how to implement the New() method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以为
T
类型参数添加约束:并在方法中
return new T();
。You could add a constraint for the
T
type parameter:and
return new T();
in the method.您应该通过添加 new() 约束来更改存储库定义,如下所示:
这将可与 MyTestRepository 一起使用的类型限制为具有默认构造函数的类型。现在,在您的 New() 方法中您可以执行以下操作:
You should change your repository definition by adding the new() constraint, like this:
This constrains types that can be used with MyTestRepository to those that have a default constructor. Now, in your New() method you can do:
假设类型 T 有一个公共/默认构造函数,这不会纠正异常吗?
Assuming type T has a public / default constructor, would this not correct the exception?
这是行不通的,因为你只是创建一个对象,没有其他任何东西。如何使用 Activator 创建对象:
请参阅:http://msdn.microsoft .com/en-us/library/system.activator.aspx
That won't work as you're just creating an object, nothing else. How about creating the object with Activator:
See: http://msdn.microsoft.com/en-us/library/system.activator.aspx