开发者

How do you make a property truly read only?

开发者 https://www.devze.com 2022-12-11 10:45 出处:网络
Take the following property: public string Foo { get; private set; } Using reflection, I can still set the value of this property from outside the owning class.Is there a way to prevent this?Removi

Take the following property:

public string Foo
{
   get;
   private set;
}

Using reflection, I can still set the value of this property from outside the owning class. Is there a way to prevent this? Removing the set accessor is not an option as it mu开发者_开发问答st be WCF friendly.


Jon Skeet says:

You can't (AFAIK) stop reflection being used in a situation where the caller has "full trust". If they're running with less than full trust then some things about reflection (if not all) are automatically disabled, I believe - however, if this is to stop other people from calling some code, you can't prevent them from running your code with full trust unless you're in control of their box in the first place.


A really ugly solution would be to use the StackTrace class to verify that only methods from your own class calls the setter.


You could obfuscate the code. This would make it hard to reflect on it.

0

精彩评论

暂无评论...
验证码 换一张
取 消