C# 属性和 this-keyword [英] C# Properties and this-keyword

查看:39
本文介绍了C# 属性和 this-keyword的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我什么时候应该对代码中的属性使用 this 关键字?

When should I use the this-keyword for properties in code?

public class MyClass {
    public string MyString { get; private set; }
    public void MyMethod() {
        OtherClass.DoStuff(MyString); // Or this.MyString?
    }
}

我知道,如果属性的类型名称相同,您必须使用 this. 使其工作.

I know that if the type and name of a property is the same you have to use this. to make it work.

public string Emailer Emailer { get { return _emailer; } }

在类中的属性甚至方法上使用this.的准则是什么?我知道它在编译后的代码中没有区别.这一切都是关于……屏住呼吸……最佳实践.

What are the guidelines for using this. on Properties and even Methods in a class? I know it makes no difference in the compiled code. It's all about... hold your breath... best practices.

推荐答案

做任何你和你的团队认为最易读的事情.有些人喜欢露骨;我只在实际需要时指定 this.它对编译后的代码没有任何影响.

Do whatever you and your team find most readable. Some people like to be explicit; I only specify this when I actually have to. It will make no difference to the compiled code.

这篇关于C# 属性和 this-keyword的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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