简体   繁体   English

您如何使某个属性真正只读?

[英]How do you make a property truly read only?

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 must be WCF friendly. 删除设置的访问器不是选项,因为它必须是WCF友好的。

Jon Skeet says : 乔恩·斯基特 Jon Skeet)

You can't (AFAIK) stop reflection being used in a situation where the caller has "full trust". 您不能(AFAIK)在呼叫者具有“完全信任”的情况下停止使用反射。 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. 我相信,如果他们以不完全信任的方式运行,那么有关反射(如果不是全部)的某些信息将自动禁用-但是,如果这是为了阻止其他人调用某些代码,则无法阻止他们运行您的代码完全信任您的代码除非您首先控制了他们的权限。

一个非常丑陋的解决方案是使用StackTrace类来验证只有您自己的类中的方法才能调用setter。

You could obfuscate the code. 您可以混淆代码。 This would make it hard to reflect on it. 这将使其难以反思。

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

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