MyClass的相当于在C# [英] MyClass equivalent in C#

查看:137
本文介绍了MyClass的相当于在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在看这个问题,评论者@乔恩埃杰顿提到 MyClass的 VB.Net 。从未使用过它,我去了,找到了文档就可以了:

In looking at this question, commenter @Jon Egerton mentioned that MyClass was a keyword in VB.Net. Having never used it, I went and found the documentation on it:

MyClass的关键字的行为就像一个对象变量引用类的当前实例最初实施。 MyClass的是与我相似,但所有的方法调用它视为如果该方法是NotOverridable。

The MyClass keyword behaves like an object variable referring to the current instance of a class as originally implemented. MyClass is similar to Me, but all method calls on it are treated as if the method were NotOverridable.

我可以看到,可能一种是有用的,在一些特定的场景。我想不到的是,你将如何获得在C#中相同的行为 - 即要确保对虚拟方法的调用 myMethod的反对<实际调用code> myMethod的在当前类,而不是派生 myMethod的(即在IL,调用通话,而不是 callvirt )?

I can see how that could kind of be useful, in some specific scenarios. What I can't think of is, how would you obtain the same behaviour in C# - that is, to ensure that a call to a virtual method myMethod is actually invoked against myMethod in the current class, and not a derived myMethod (a.k.a in the IL, invoking call rather than callvirt)?

我可能只是有一个完整的精神空白的时刻虽然。

I might just be having a complete mental blank moment though.

推荐答案

据乔恩斯基特,有没有这样的等价的:

According to Jon Skeet, there is no such equivalent:

没有,C#没有按'吨有VB.NET的MyClass的关键字的等效。如果要保证不调用方法的重写版本,你需要使它非虚摆在首位。

No, C# doesn't have an equivalent of VB.NET's MyClass keyword. If you want to guarantee not to call an overridden version of a method, you need to make it non-virtual in the first place.

这是显而易见的解决办法是这样的:

An obvious workaround would be this:

public virtual void MyMethod()
{
    MyLocalMethod();
}

private void MyLocalMethod()
{
    ...
}

然后,你可以调用 MyLocalMethod()当VB用户会写 MyClass.MyMethod( )

Then you could call MyLocalMethod() when a VB user would write MyClass.MyMethod().

这篇关于MyClass的相当于在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆