繁体   English   中英

如何在C#中定义属性而不是公共变量

[英]How to define a property instead of public variable in C#

public static string SEARCH_STRING = "searchkey";
string key=Request.QueryString.Get(SEARCH_STRING);    

如何更改上面的代码以使用Property(get; set;)而不是公共变量来访问SEARCH_STRING

private static string _searchString = "searchkey";
public static string SearchString { 
  get { return _searchString; }
  set { _searchString = value; }
}

如果不更改此变量,则最好使用常量

public const string SEARCH_STRING = "searchkey";

这就是你如何使其成为财产

private static string _searchString = "searchkey";
public static string SEARCH_STRING { 
  get { return _searchString; }
  private set { _searchString = value; }
}
public static string SEARCH_STRING { get; set; }

试试这个代码:

class Foo {
static string m_searchString="searchKey";
public static string SEARCH_STRING
{
   get {return m_searchString;}
   set {m_searchString=value;}
}
}

这是你的意思吗? 如果您要在运行时加载其值,也可以将其设置为只读...

public static string SEARCH_STRING 
{ 
    get
    {
        return "searchkey";
    }
}
public string SEARCH_STRING
    {
        get { return search_string; }
        set { search_string = value; }
    }
public static string SEARCH_STRING
    {
        get;
        set;
    }

要进行更多封装,请使用以下属性:

public string Name
{
    get;
    private set;
}

因此该类的对象只能设置它,其他对象只能读取它。

暂无
暂无

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

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