C# 是否可以将委托约束到类型的成员?
我想将委托约束到类型的成员。例如C# 是否可以将委托约束到类型的成员?,c#,delegates,C#,Delegates,我想将委托约束到类型的成员。例如 class Foo { public virtual void Bar() {} } class Baz : Foo { public override void Bar() { this.BarAndMore(base.Bar); } } delegate void FooMemberDelegate(); // Can I restrict this so `FooMemberDelegate`s can only b
class Foo {
public virtual void Bar() {}
}
class Baz : Foo {
public override void Bar() {
this.BarAndMore(base.Bar);
}
}
delegate void FooMemberDelegate(); // Can I restrict this so `FooMemberDelegate`s can only be assigned to members of Foo
static class Extensions {
public static void BarAndMore(this Foo foo, FooMemberDelegate fooMemberDelegate) {
// Other stuff
fooMemberDelegate();
// More stuff
}
}
编辑:似乎是类似的的副本。你能解释一下你想解决什么问题吗?我想限制我正在完成的库的使用。问题是,我的库可能被使用的一个常见情况是,
Baz
必须从Foo
继承,因此我必须采取扩展方法解决方法。对于上下文,这里是我的库的一部分,我想约束baseSaveChanges
参数。编辑:Ooops实际上并没有发布链接,如果你好奇的话,常见的情况是用户的DbContext
类继承自IdentityDbContext
,因此用户可以获得所有好的标识库内容。我还不完全清楚为什么需要这个,但没有编译时方法来阻止它,如果您感兴趣,可以通过检查Delegate.Method
属性来执行此运行时,如果不满足您的需要,则抛出异常。