[英]readonly parameter with container Class (C#)
好的,假設我有一個數據容器類
public class DataContainer {
public Person person;
}
我們已經創建了這個類的一個實例
DataContainer dataContainer = new DataContainer();
dataContainer.Person = new Person("Smith");
我們嘗試將它傳遞給我們希望能夠只讀取容器而不修改的方法
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
}
我嘗試了 in 關鍵字,但它對禁止更改容器沒有任何影響...
PS:將容器轉換為結構體是沒有解決方案的,因為它會變得不可變
如果您不想能夠修改 Person.Name,那么您可以簡單地使用封裝。
我將按以下方式設計 Person 類:
class Person
{
public Person(string name)
{
Name = name;
}
public string Name { get; }
}
如果這沒有幫助,那么我看到的唯一其他方法是將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.