【发布时间】:2011-01-12 15:01:46
【问题描述】:
例如给定一个带有方法的工厂
public static T Save<T>(T item) where T : Base, new()
{
/* item.Id == Guid.Empty therefore item is new */
if (item.Id == Guid.Empty && repository.GetAll<T>(t => t.Name == item.Name))
{
throw new Exception("Name is not unique");
}
}
如何创建Base(比如MustNotAlreadyExist)的属性,以便我可以将上面的方法更改为
public static T Save<T>(T item) where T : Base, new()
{
/* item.Id == Guid.Empty therefore item is new */
if (item.Id == Guid.Empty && repository.GetAll<T>(t.MustNotAlreadyExist))
{
throw new Exception("Name is not unique");
}
}
public class Base
{
...
public virtual Expression<Func<T, bool>> MustNotAlreadyExist()
{
return (b => b.Name == name); /* <- this clearly doesn't work */
}
}
然后我如何覆盖 Account : Base 中的 MustNotAlreadyExist
public class Account : Base
{
...
public override Expression<Func<T, bool>> MustNotAlreadyExist()
{
return (b => b.Name == name && b.AccountCode == accountCode); /* <- this doesn't work */
}
...
}
【问题讨论】:
-
我认为我可能有方法签名,尽管我正在努力解决它: public virtual Expression
> MustNotAlreadyExists (T item) where T : Base { return (t => t.Name == item.Name); } -
在下面查看我自己的答案;使用泛型接口并为类型中的特定类型实现此接口
标签: c# generics lambda virtual