简体   繁体   English

带有容器类的只读参数(C#)

[英]readonly parameter with container Class (C#)

Ok so let's say that I have a data container class好的,假设我有一个数据容器类

public class DataContainer {
      public Person person;
}

and we already create an instance of this class我们已经创建了这个类的一个实例

DataContainer dataContainer = new DataContainer();
dataContainer.Person = new Person("Smith");

and we try to pass it in a method that we want to be able to only read the container and not modified我们尝试将它传递给我们希望能够只读取容器而不修改的方法

public void ExampleMethod(in DataContainer dataContainer){
   dataConainer.Person.name = "blablabla" //we don't want to be able to do that
   dataContainer = new DataContainer(); // this is not possible because of in keyword
}

I tried the in keyword but it doesn't have any effect on prohibiting changes on container...我尝试了 in 关键字,但它对禁止更改容器没有任何影响...

PS : convert the container into a struct is no solution because it will become immutable PS:将容器转换为结构体是没有解决方案的,因为它会变得不可变

If you don't want to be able to modify the Person.Name, then you could simply use encapsulation.如果您不想能够修改 Person.Name,那么您可以简单地使用封装。

I would design the Person class in the following way:我将按以下方式设计 Person 类:

class Person
{
    public Person(string name)
    {
        Name = name;
    }

    public string Name { get; }
}

If this doesn't help, then the only other approach I see is to pass a DTO to ExampleMethod (which can be easily created using Automapper ).如果这没有帮助,那么我看到的唯一其他方法是将DTO传递给ExampleMethod (可以使用Automapper轻松创建)。

var dto = _mapper.Map<DataContainerDto>(dataContainer);
ExampleMethod(dto);

...

public void ExampleMethod(DataContainerDto dataContainer)
{
    // Nobody cares if I modify it,
    // because the original dataContainer reamains intact
    dataConainer.Person.name = "blablabla";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM