寻找在基类中实现功能的通用方法
-
29-09-2019 - |
题
我正在尝试在域层中简单地实现规范模式。
如果我的静态课程充满了这样的规格:
public static class FooSpecifications
{
public static Func<Foo, bool> IsSuperhuman
{
get
{
return foo => foo.CanShootLasersOutOfItsEyes && foo.CanFly;
}
}
}
然后,我可以做这样的奇妙事情:
IEnumerable<Foo> foos = GetAllMyFoos();
var superFoos = foos.Where(FooSpecifications.IsSuperhuman);
我还可以将Bool方法添加到FOO中,以确定特定实例是否符合规范:
public bool Meets(Func<Foo, bool> specification)
{
return specification.Invoke(this);
}
鉴于FOO像我所有的域实体一样扩展了域名,我是否可以将METES()的通用实现放入domainObject中,以节省我在每个实体中分别实现meets()?
解决方案
这样的东西...
public abstract class DomainObj<T> // T - derived type
where T : DomainObj<T>
{
public bool Meets(Func<T, bool> specification)
{
return specification.Invoke((T) this);
}
}
public class Foo : DomainObj<Foo> {}
public class Bar : DomainObj<Bar> {}
Func<Foo, bool> foospec = x => true;
Func<Bar, bool> barspec = x => true;
var foo = new Foo();
var bar = new Bar();
foo.Meets(foospec);
foo.Meets(barspec); // won't compile because of mismatched types of spec and object instance
编辑
也许最好将Meet方法转换为扩展。这将消除类型参数的需求。
public abstract class DomainObj
{
}
public static class DomainObjExtensions
{
public static bool Meets<T>(this T obj, Func<T, bool> f)
where T : DomainObj
{
return f(obj);
}
}
public class Foo : DomainObj {}
public class Bar : DomainObj {}
Func<Foo, bool> foospec = x => true;
Func<Bar, bool> barspec = x => true;
var foo = new Foo();
var bar = new Bar();
foo.Meets(foospec);
foo.Meets(barspec); // error
不隶属于 StackOverflow