简体   繁体   English

在C#中获取和设置问题

[英]Problem with getting and setting in C#

I am trying to assign a line of text as a string, so the string can be used in a message box, although the string fails to show up in the message box when the method is executed. 我正在尝试将一行文本指定为一个字符串,因此该字符串可以在消息框中使用,尽管在执行该方法时该字符串无法在消息框中显示。

public string version { get; set; }

public void GetVersion()
{
    var version = File.ReadAllText("version.txt");
}


private void SetBalloonTip()
{
    notifyIcon1.Icon = SystemIcons.Exclamation;
    notifyIcon1.BalloonTipTitle = "Test";
    notifyIcon1.BalloonTipText = "This is version " + version;
    notifyIcon1.BalloonTipIcon = ToolTipIcon.Error;
    this.Click += new EventHandler(button1_Click);
}

Remove the var : 删除var

version = File.ReadAllText("version.txt");

By adding the var (or any variable type for that matter) you're creating local variable, while you want to assign the class member. 通过添加var (或与此相关的任何变量类型),您可以在创建本地变量的同时分配类成员。

Happens to me too sometimes, and I see this as downside of C# as I would expect at least a warning when compiling such a thing. 有时也会发生在我身上,我认为这是C#缺点,因为我期望编译这样的事情时至少会发出警告。

You are declaring a local variable with "var version", which is separate from your property "version". 您正在使用“ var version”声明局部变量,该变量与属性“ version”分开。 Just replace "var version" with "this.version" or just "version". 只需将“ var version”替换为“ this.version”或“ version”即可。

var version = ... shadows the property with a local variable; var version = ...用局部变量遮盖属性; meaning, the assignment is stored in a local variable named version , not the property named version . 这意味着,分配存储在一个局部变量命名的version ,没有命名的属性version

this.version = ... will do what you want. this.version = ...将做您想要的。

By the way, out of convention in C#, local variables begin with lowercase letters as you have, but properties begin with an uppercase letter -- conventions like these may help alleviate shadowing issues as you experienced here. 顺便说一句,在C#中,约定俗成,局部变量以小写字母开头,而属性以大写字母开头-像这样的约定可能有助于减轻您在此处遇到的阴影问题。

if you are using var here, you should also be aware of its purpose and implication. 如果您在此处使用var ,则还应了解其用途和含义。 never use anything that you are not familiar with. 切勿使用您不熟悉的任何东西。 This is just thumb rule. 这只是经验法则。

As mentioned above, using proper casing for class member and accessing class member with this. 如上所述,为类成员使用适当的大小写并以此访问类成员 are best practices. 是最佳做法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM