开发者

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

开发者 https://www.devze.com 2023-02-20 00:01 出处:网络
public static string SEARCH_开发者_C百科STRING = \"searchkey\"; string key=Request.QueryString.Get(SEARCH_STRING);
public static string SEARCH_开发者_C百科STRING = "searchkey";
string key=Request.QueryString.Get(SEARCH_STRING);    

How to change the above code to make SEARCH_STRING be accessed using a Property(get; set;) instead of a public variable


If this variable will not be changed, it is better to use constant

public const string SEARCH_STRING = "searchkey";

and here is how you can make it property

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


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


public static string SEARCH_STRING { get; set; }


Try this code:

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


is this what you're meaning? can probably set it to be readonly also if you're going to load its value at runtime...

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;
    }


For more encapsulation, use properties like this:

public string Name
{
    get;
    private set;
}

so the object of that class only can set it, other objects can read it only.

0

精彩评论

暂无评论...
验证码 换一张
取 消