将成员变量声明为只读有什么好处?它只是防止在类的生命周期中更改某些人,或者是否由于此关键字而导致编译器速度提高
我在MSDN上发现了一个话题,是的,这是可能的.
我做了一个似乎打破了这个声明的测试:
using System;
namespace Test
{
class Program
{
static void Main(string[] args)
{
Foo f = new Foo("1");
Console.WriteLine(f.Bar); // prints 1
f.Test("2");
Console.WriteLine(f.Bar);// successfully prints 2
}
}
class Foo
{
public Foo(string b)
{
this.Bar = b;
}
public string Bar { get; private set; }
public void Test(string b)
{
// this would be impossible for readonly field!
// next error would be occur: CS0191 or CS0191
// A readonly field cannot be …Run Code Online (Sandbox Code Playgroud) 自动属性让我替换此代码:
private MyType myProperty;
public MyType MyProperty
{
get { return myPropertyField; }
}
Run Code Online (Sandbox Code Playgroud)
使用此代码:
public MyType MyProperty { get; private set; }
Run Code Online (Sandbox Code Playgroud)
在这里和那里进行一些更改 - 但有没有办法替换此代码:
private readonly MyType myProperty;
public MyType MyProperty
{
get { return myPropertyField; }
}
Run Code Online (Sandbox Code Playgroud)
有类似的东西?
在我的 .net core 3.1 应用程序中,我想将属性封装在某个实体中:
public class Sample : AuditableEntity
{
public Sample(string name)
{
Name = name;
}
public int Id { get; }
public string Name { get; }
}
Run Code Online (Sandbox Code Playgroud)
因此,我删除了所有公共设置器,因此当我想检查此类 Sample 是否已存在时,我的代码中的某个位置
_context.Samples.Any(r => r.Name == name)
Run Code Online (Sandbox Code Playgroud)
该行导致错误:System.InvalidOperationException: 'No suitable constructor found for entity type 'Sample'. The following constructors had parameters that could not be bound to properties of the entity type: cannot bind 'name' in 'Sample(string name)'.'。
所以我添加了代码空构造函数
public class Sample : AuditableEntity
{ …Run Code Online (Sandbox Code Playgroud) .net c# entity-framework-core .net-core entity-framework-core-3.1