不允许更改对象

c#

我有一个只读对象,但它的属性在某处得到更新。是否C#有任何限制也可以通过直接更改和反射来限制?

这是POC代码

class Program
{
    static void Main(string[] args)
    {
        ReadOnlyCreator tester = new ReadOnlyCreator();
        tester.ModifyTester();
        Console.ReadLine();
    }
}

class ClassUnderTest
{
    public string SomeProp { get; set; }
}

class ReadOnlyCreator
{
    private readonly ClassUnderTest _classUnderTest;
    public ReadOnlyCreator()
    {
        _classUnderTest = new ClassUnderTest { SomeProp = "Init" };
    }

    public void ModifyTester()
    {
        Console.WriteLine("Before: " + _classUnderTest.SomeProp);
        var modifier = new Modifier(_classUnderTest);
        modifier.Modify();
        Console.WriteLine("After: " + _classUnderTest.SomeProp);
    }
}
class Modifier
{
    private ClassUnderTest _classUnderTest;
    public Modifier(ClassUnderTest classUnderTest)
    {
        _classUnderTest = classUnderTest;
    }

    public void Modify()
    {
        _classUnderTest.SomeProp = "Modified";
    }

回答

如果你想要一个只读对象,你应该让它只读。IE

class ClassUnderTest
{
    public string SomeProp { get;  }
    public ClassUnderTest(string someProp) => SomeProp = someProp;
}

如果您使用的是 c#9,您也可以使用init only setter。这允许仅在构造对象期间设置属性:

class ClassUnderTest
{
    public string SomeProp { get; init; }
}

如果您使用值类型,您可以(并且应该)将整个类型声明为只读。另请参阅在类和结构之间进行选择

public readonly struct StructUnderTest

这不能防止反射或不安全的代码。使用这些功能是故意规避规则,因此由开发人员来确保其安全。

  • @Liam `struct` by itself doesn't make it immutable; it is the `readonly` in the `readonly struct` that does this, and: that's *what OP wants*; there are *other* implications of the `struct` part though - around equality, boxing, copy-by-value, and a few other things that are far more relevant
  • @Imad The first example works just fine in c# 8 and earlier. You will need to create a constructor, but that is usually a good idea anyway to ensure all properties are actually set.

以上是不允许更改对象的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>