我正在尝试创建类的属性,这些属性只能通过同一类的构造函数进行设置。
What is the use of default keyword in C#? Is it introduced in C# 3.0 ?
我正在尝试创建类的属性,这些属性只能通过同一类的构造函数进行设置。
使属性具有只读的备份字段:
public class Thing
{
private readonly string _value;
public Thing(string value)
{
_value = value;
}
public string Value { get { return _value; } }
}
You can make an immutable property in two ways. You can declare the set accessor.to be private. The property is only settable within the type, but it is immutable to consumers. You can instead declare only the get accessor, which makes the property immutable everywhere except in the type’s constructor.
在Visual Studio 2015中包含的 C# 6.0 中,有一个更改可允许从构造函数设置只读属性,而且只能从构造函数中设置。
因此,该代码可以简化为仅是获取属性:
public class Thing
{
public Thing(string value)
{
Value = value;
}
public string Value { get; }
}
C# 9 引入了 init 关键字,它是 set 的变体,这是最好的做法。
The one big limitation today is that the properties have to be mutable for object initializers to work: They function by first calling the object’s constructor (the default, parameterless one in this case) and then assigning to the property setters.
Init-only properties fix that! They introduce an init accessor that is a variant of the set accessor which can only be called during object initialization:
public class Person
{
public string FirstName { get; init; }
public string LastName { get; init; }
}
从C#6.0开始,您现在可以拥有仅可获取的属性,这些属性可以在构造函数中设置(即使在属性本身中未定义set)。参见Property with private setter versus get-only-property
What is the use of default keyword in C#? Is it introduced in C# 3.0 ?
I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...
I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...
I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...
I have two EF entities. One has a property called HouseNumber. The other has two properties, one called StartHouseNumber and one called EndHouseNumber. I want to create a many to many association ...
How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...
Since I cannot order my dictionary, what is the best way of going about taking key value pairs and also maintaing an index?
Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...