如何使用私有方法调整 ac# 类?
我想用私有方法调整一个类,以便适配器调用这个私有方法:
考虑这个类
public class Foo
{
private void bar()
}
我想要一个遵循命令模式的类,并在它的执行方法中调用 bar() :
public class FooCommand
{
private Foo foo_;
public FooCommand(Foo foo)
{
foo_ = foo;
}
public void execute()
{
foo.bar();
}
}
任何想法都会很好赞赏。
谢谢!
I would like to adapt a class with a private method, so that the adapter calls this private method:
Consider this class
public class Foo
{
private void bar()
}
I would like a class that follows the command pattern, and calls bar() in it's execute method:
public class FooCommand
{
private Foo foo_;
public FooCommand(Foo foo)
{
foo_ = foo;
}
public void execute()
{
foo.bar();
}
}
Any ideas would be greatly appreciated.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我相信有很多选择:
使用带有
Execute
方法的接口ICommand
,而不是FooCommand
。然后以实现ICommand
的方式声明Foo
:我相信这是最有吸引力的解决方案:该方法仍然可以是私有的;您不需要为每个
Foo
实例化额外的FooCommand
;并且您不需要为每个需要它的X
类声明一个单独的XCommand
类。在
Foo
类中声明FooCommand
类,使其成为嵌套类。然后FooCommand
就可以访问私有方法。声明
bar
方法公共或内部。声明
bar
方法受保护或受保护内部,然后从Foo
派生FooCommand
code>.使用反射调用私有方法(使用
Type.GetMethod
后跟MethodBase.Invoke
)。我相信大多数开发人员都会认为这是一个肮脏的黑客行为。I believe there are many options:
Instead of a
FooCommand
, use an interfaceICommand
with anExecute
method. Then declareFoo
in such a way that it implementsICommand
:I believe this is the most attractive solution: the method can still be private; you don’t need to instantiate an extra
FooCommand
for everyFoo
; and you don’t need to declare a separateXCommand
class for everyX
class that wants it.Declare the
FooCommand
class inside theFoo
class so that it becomes a nested class. Then theFooCommand
can access the private method.Declare the
bar
method public or internal.Declare the
bar
method protected or protected internal and then deriveFooCommand
fromFoo
.Use Reflection to invoke the private method (use
Type.GetMethod
followed byMethodBase.Invoke
). I believe most developers would consider this a dirty hack.您至少需要将 bar() 设为受保护而不是私有。私有函数只能由声明它们的类调用,除非您决定使用反射,从而对您的应用程序提出安全要求。
You would need to at least make bar() protected rather than private. Private functions can only be called by the class that declares them, unless you decide to use Reflection which then places security requirements on your application.
执行此操作的唯一方法是使用反射并以这种方式调用该方法,但是我强烈建议不要这样做。为什么不直接将该方法设为内部方法呢?
The only way to do this would be to use reflection and invoke the method that way, however I would strongly suggest against doing that. Why not just make the method internal?
我同意其他发帖者的观点,他们说将方法设为内部方法并在需要时使用InternalsVisibleToAttribute。
I agree with the other posters who say make the method internal and use InternalsVisibleToAttribute if needed.
您是否有权访问 Foo 类,就像访问修改类一样?如果没有,我不相信你可以从另一个类调用它的私有方法 bar() 。
Do you have access to class Foo as in access to modify the class? If not, I don't believe you can call its private method bar() from another class.