Shouldn't I get a compiler warning for this? how do I enable it?
let's say i have this
public class MyClass
{
public string myMessage { get; set; }
void MyMethod()
{
string myMessage;
}
}
shouldn't i get an alert about myMessage
in MyMe开发者_如何学编程thod
hiding(?) the myMessage
property on the class? i'm not getting anything to this effect when i build. how do i activate this check?
The problem here is that we have no way of distinguishing between a valid, desired case of hiding and an accidental case of hiding. We try to reserve warnings for situations where (1) the code is almost certainly wrong and (2) there is a straightforward way to rewrite the code so that the warning is eliminated if the code as stated is in fact desired.
This is often a desired case because of this:
class Frog
{
private string name;
public Frog(string name)
{
this.name = name;
You don't want to change the field "name" to something else because it is perfectly descriptive as-is. You don't want to change the parameter "name" to something else because you want to be able to do new Frog(name: "Kermit")
in C# 4 or Visual Basic. Since the hiding is desired and the code is correct we don't want to produce a warning for the hiding.
I know of no warning for this condition. Within MyMethod()
, you can use this.myMessage
to disambiguate between the local and the class property.
Just FYI, properties are usually TitleCased while locals are camelCased. Using that convention can prevent naming clashes like the one you list.
Check out Lexical Scoping. The myMessage inside MyMethod is defined in a new scope. Any reference to myMessage within that method will assume you are referring to the variable defined in that scope. You can access the myMessage defined in MyClass by using this.myMessage.
EDIT: Given that info, you can see why this is perfectly valid from the compiler's perspective. Whether or not it should give you a warning is interesting. As Mitch Wheat pointed out in his comment, a tool like ReSharper will warn you about these things, but it's debatable if a compiler should warn you about collisions for something which it handles with lexical scoping. Seems like more of a job for a complementary tool.
This is actually in accordance with one naming pattern for private fields, though I prefer _fieldName myself:
public class MyClass
{
private string myMessage;
public MyClass(string myMessage)
{
this.myMessage = myMessage;
}
}
精彩评论