[英]Writing to a read-only accessor c#
I'm trying to make something similar to ASP.NET's User.Identity.Name. 我正在尝试制作类似于ASP.NET的User.Identity.Name。 I've already made the class to hold the information but I don't know how to write to the variable since I only added the get{};
我已经让类保存了这些信息,但我不知道如何写入变量,因为我只添加了get {};
private static string _firstName;
public static string FirstName
{
get { return _firstName; }
}
There are 2 ways to do this. 有两种方法可以做到这一点。 The first way is adding a private setter.
第一种方法是添加私有的setter。
private static string _firstName;
public static string FirstName
{
get { return _firstName; }
private set { _firstName = value; }
}
The other option is add a parameter to your constructor and set the value inside it. 另一个选项是向构造函数添加一个参数并在其中设置值。
public YourClass(string firstName)
{
_firstName = firstName;
}
public class YourAwesomeClass
{
private static string _firstName;
public static string FirstName
{
get { return _firstName; }
}
public YourAwesomeClass(string firstName)
{
_firstName=firstName;
}
}
or you if are using Dotnet 3.0 or greater you can use automatic property, Compiler will automatically create backing fields for you. 或者如果您使用的是Dotnet 3.0或更高版本,则可以使用自动属性,编译器会自动为您创建支持字段。
public class YourAwesomeClass
{
public static string FirstName
{
get;private set;
}
public YourAwesomeClass(string firstName)
{
FirstName=firstName;
}
}
Write a setter methode: 写一个setter方法:
public static string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.