扩展方法试图调用受保护的方法/错误显示动态参数 [英] Extensions Method trying to call protected methods / wrong exhibition of dynamic parameters
问题描述
我有一个名为NIFERepository
的类.它包含一个SaveObject
方法,该方法不返回任何内容并在数据库上执行操作.
I have a class named NIFERepository
. It contains a SaveObject
method, which returns nothing and performs an operation on a database.
public class NIFERepository<E>
{
protected void SaveObject(object saveObject)
{
if (saveObject is E)
this.RepositorySession.Merge(saveObject);
}
}
1.我希望创建一个公共扩展方法来调用此SaveObject()
方法,如下所示:
1 . I wish to create a public extension method who calls this SaveObject()
method, like this:
public static class NIFERepositoryExtensions
{
public static T Save<T, E>(this T self, E saveObject) where T : NIFERepository<E>
{
self.SaveObject(saveObject);
return self;
}
}
但是受保护的范围不允许我的扩展方法识别它.
But the protected scope doesn't allow my extensions method to recognize it.
我有办法让这种形式的方法起作用吗?
Is there a way for me to get a method of this form to work?
2.我创建了2种类型的扩展方法:T
和E
.例如,T
是调用它的实例,而E
是我的ProductRepository<Product>
中定义的类型.当我调用此方法时,未显示定义的类型.
2 . I created my extension method with 2 types: T
and E
. T
is the instance who called it, and E
is the defined type into my ProductRepository<Product>
, for example. When I call this method, the defined type is not shown.
我有办法让它正常工作吗?
Is there a way for me to get this to work?
推荐答案
- 您不能使用扩展方法来违反封装.
如果该类未公开该方法,则无法调用该方法(Reflection除外).
由于某种原因,该方法(希望是)是protected
;您可能做错了事.
- You cannot use extension methods to violate encapsulation.
If the class does not expose the method, you can't call it (except with Reflection).
The method is (hopefully)protected
for a reason; you're probably doing something wrong.
这篇关于扩展方法试图调用受保护的方法/错误显示动态参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!