C# 从 get 返回一个只读变量;放;
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/939563/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# return a variable as read only from get; set;
提问by Jon
I swear I have seen an example of this but have been googling for a bit and can not find it.
我发誓我见过这样的一个例子,但已经在谷歌上搜索了一段时间并找不到它。
I have a class that has a reference to an object and need to have a GET; method for it. My problem is that I do not want anyone to be able to fiddle with it, i.e. I want them to get a read only version of it, (note I need to be able to alter it from within my class).
我有一个类,它有一个对象的引用并且需要一个 GET;方法。我的问题是我不希望任何人能够摆弄它,即我希望他们获得它的只读版本,(注意我需要能够在我的班级中改变它)。
Thanks
谢谢
采纳答案by Jon Skeet
No, there's no way of doing this. For instance, if you return a List<string>
(and it's not immutable) then callers willbe able to add entries.
不,没有办法做到这一点。例如,如果您返回 a List<string>
(并且它不是不可变的),那么调用者将能够添加条目。
The normal way round this is to return an immutable wrapper, e.g. ReadOnlyCollection<T>
.
解决这个问题的正常方法是返回一个不可变的包装器,例如ReadOnlyCollection<T>
.
For other mutable types, you may need to clone the value before returning it.
对于其他可变类型,您可能需要在返回值之前克隆该值。
Note that just returning an immutable interface view (e.g. returning IEnumerable<T>
instead of List<T>
) won't stop a caller from casting back to the mutable type and mutating.
请注意,仅返回不可变的接口视图(例如,返回IEnumerable<T>
而不是List<T>
)不会阻止调用者转换回可变类型并进行变异。
EDIT: Note that apart from anything else, this kind of concern is one of the reasons why immutable types make it easier to reason about code :)
编辑:请注意,除此之外,这种担忧是不可变类型使代码更容易推理的原因之一:)
回答by Anton Gogolev
Return a reference to a stripped-down interface:
返回对精简接口的引用:
interface IFoo
string Bar { get; }
class ClassWithGet
public IFoo GetFoo(...);
回答by Jamie Ide
This isn't possible. Get and set accessors to reference types get and set the reference to the object. You can prevent changes to the reference by using a private (or internal) setter, but you cannot prevent changes to the object itself if it's exposed by a getter.
这是不可能的。获取和设置访问器到引用类型获取和设置对对象的引用。您可以使用私有(或内部)setter 来阻止对引用的更改,但如果对象由 getter 公开,则无法阻止对对象本身的更改。
回答by justlost
If the object isn't too complicated/extensive then write an wrapper around it.
如果对象不是太复杂/广泛,则围绕它编写一个包装器。
for example:
例如:
class A {
public string strField = 'string';
public int intField = 10;
}
class AWrapper {
private A _aObj;
public AWrapper(A aobj) {
_aObj = A;
}
public string strField {
get {
return _aObj.strField;
}
}
public int intField {
get {
return _aObj.intField;
}
}
}
So now all you do is give your client code an instance of the AWrapper class so that they may only use what you allow them to see.
所以现在你要做的就是给你的客户端代码一个 AWrapper 类的实例,这样他们就可以只使用你允许他们看到的东西。
this may get a bit complicated and may not scale well if your base class is not set in stone, but for most simple situation it may just do the trick. I think this is called a facade pattern(but don't quote me on that =) )
如果您的基类不是一成不变的,这可能会变得有点复杂并且可能无法很好地扩展,但对于大多数简单的情况,它可能只是解决问题。我认为这被称为外观模式(但不要在那个上引用我 =))
回答by pingsft
i agree with ReadOnlyCollection
我同意 ReadOnlyCollection
See my simple code:
看我的简单代码:
private List<Device> _devices;
public readonly System.Collections.ObjectModel.ReadOnlyCollection<Device> Devices
{
get
{
return (_devices.AsReadOnly());
}
}
}
ReadOnlyCollection dosen't has Add method so user cant add properties to it.BUT ther is no warranty that if user can modify objects by calling their methods....
ReadOnlyCollection 没有 Add 方法,因此用户无法向其添加属性。但不能保证用户是否可以通过调用其方法来修改对象....
回答by Matt
Your question reads like you're looking for:
你的问题读起来就像你在寻找:
public PropertyName { get; private set; }
But then, given the answers so far I'm not sure I'm interpreting your question correctly. Besides, who am I to question Jon Skeet? :)
但是,鉴于到目前为止的答案,我不确定我是否正确解释了您的问题。此外,我是谁来质疑乔恩斯基特?:)
回答by cdie
I have faced this problem in a certain way. I have a CategoryViewModel class, which have a property Category that I want private read-only :
我以某种方式面对过这个问题。我有一个 CategoryViewModel 类,它有一个我想要私有只读的属性 Category :
public CategoryViewModel
{
private Category { get; }
}
In fact, I want it to be exported as read-only to other class. However I can't do such thing. In my case (maybe it will help some other guys), I want to add it to a repository. The only way that I've found is to have a function with the repository as param 1, and an Action as param 2 :
事实上,我希望它以只读方式导出到其他类。但是我不能做这样的事情。就我而言(也许它会帮助其他人),我想将它添加到存储库中。我发现的唯一方法是将存储库作为参数 1 的函数和作为参数 2 的操作:
public void ApplyAction(ICategoryRepository repo, Action<ICategoryRepository, Category> action)
{
action(repo, Category);
}
Like that, from elsewhere, I can do such thing :
像那样,从其他地方,我可以做这样的事情:
categoryViewModel.ApplyAction(_repository, (r, c) => r.MarkForInsertOrUpdate(c));
This can help other to expose there property only for certains cases and can manage them.
这可以帮助其他人仅在某些情况下公开那里的财产并可以管理它们。