相关疑难解决方法(0)

你什么时候使用"this"关键字?

我很好奇其他人如何使用this关键字.我倾向于在构造函数中使用它,但我也可以在其他方法中使用它.一些例子:

在构造函数中:

public Light(Vector v)
{
    this.dir = new Vector(v);
}
Run Code Online (Sandbox Code Playgroud)

别处

public void SomeMethod()
{
    Vector vec = new Vector();
    double d = (vec * vec) - (this.radius * this.radius);
}
Run Code Online (Sandbox Code Playgroud)

c# coding-style this

248
推荐指数
11
解决办法
19万
查看次数

为什么StyleCop建议使用"this"作为前缀方法或属性调用?

我一直在尝试遵循StyleCop关于项目的指导原则,看看最终的代码是否更好.大多数规则都是合理的,或者是关于编码标准的意见问题,但有一条规则让我感到困惑,因为我没有看到其他人推荐它,而且因为我没有看到明显的好处:

SA1101:对{method或property name}的调用必须以'this'开头.前缀表示该项是该类的成员.

在缺点方面,代码显然更加冗长,遵循该规则有什么好处?这里有人遵循这条规则吗?

.net c# coding-style stylecop

67
推荐指数
6
解决办法
2万
查看次数

何时不使用'this'关键字?

很抱歉再次询问,已经有一些关于此关键字的问题.但他们所有人都说出了"这个"的目的.

什么时候使用这个关键字
C#何时使用此关键字
在C#中使用静态方法的形式参数中的"this"关键字在C#中
正确使用"this."关键字?

我的问题是何时不使用'this'关键字.
或者
在代码之类的情况下始终使用此关键字是否正确

class RssReader
{
    private XmlTextReader _rssReader;
    private XmlDocument _rssDoc;
    private XmlNodeList _xn;

    protected XmlNodeList Item { get { return _xn; } }
    public int Count { get { return _count; } }

    public bool FetchFeed(String url)
    {
        this._rssReader = new XmlTextReader(url);
        this._rssDoc = new XmlDocument();
        _rssDoc.Load(_rssReader);
        _xn = _rssDoc.SelectNodes("/rss/channel/item");
        _count = _xn.Count;
        return true;
    }
}
Run Code Online (Sandbox Code Playgroud)

这里我没有使用'this'和"_xn"和"_count"也没有使用"_rssDoc.Load(_rssReader);" 好吗?我应该在类中使用"this"以及所有类变量吗?

编辑:在类中为自己的变量使用'this' 是没用的吗?

c# this this-keyword

12
推荐指数
4
解决办法
6531
查看次数

C#StyleCop - 使用"this".基类成员的前缀,如当前的类成员与否?

StyleCop有一个关于使用"this"的规则.调用类成员的前缀(SA1101).

这个规则是否适用于从其基类继承的类的成员(例如方法).

例:

class BaseClass
{
    protected void F1()
    {
        ...
    }
}    

class ChildClass : BaseClass
{
    protected void F2()
    {
        ...
    }

    protected void F3()
    {
        this.F2(); // This is correct acording to SA1101

        // F1 is a member of base class and if I dont put this prefix, stylecop will not show any message.
        this.F1(); // Is this correct?
        F1();      // Or this?
    }
}
Run Code Online (Sandbox Code Playgroud)

我知道这只是为了更好的可读性.

c# coding-style stylecop this

8
推荐指数
2
解决办法
6695
查看次数

标签 统计

c# ×4

coding-style ×3

this ×3

stylecop ×2

.net ×1

this-keyword ×1