Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/unix/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何保护属性不被覆盖_C# - Fatal编程技术网

C# 如何保护属性不被覆盖

C# 如何保护属性不被覆盖,c#,C#,我有一门课: public class Foo { // here so serializer can materialize the class public Foo(){ } public Foo(string bar){ ImportantStuff = bar; } public string ImportantStuff { get; set;} public string OtherBits{ get; set;} public int eresting { get;

我有一门课:

public class Foo {
// here so serializer can materialize the class
public Foo(){

}

public Foo(string bar){
    ImportantStuff = bar;
}

public string ImportantStuff { get; set;}
public string OtherBits{ get; set;}
public int eresting { get; set;}

}

如何保护除序列化程序(json.net/EF)之外的任何人设置的
importantsttuff

您可以在属性访问器上放置访问修饰符

[JsonProperty]
public string ImportantStuff { get; private set; }
//                                    ^^^
如果确实必须阻止
Foo
成员更改它,请使用
private
setter并将属性移动到基类。但我对这个问题的解释是,你不希望这个类的消费者能够设置它

JsonProperty
属性是必需的,因为JSON.net将默认跳过带有非公共setter的属性。看到和


(当然,其他以完全权限运行的代码可以对对象内部执行任何它想执行的操作,只要跳过正确的环)

public readonly string ImportantStuff
@AmitJoki:序列化程序使用反射和绕过权限。该类的普通客户端将受到该权限的限制。限制同一类的其他成员的方法不多。@BenVoigt,你是对的,我不希望类外的任何人能够设置它,但序列化程序能够,我将使用private进行测试并接受答案是的,你是对的,我有,但没有你有那么多。但我很肯定,当我到了你这个年龄时,我会得到更多关于这方面的信息;)@艾米特:与专家意见相左没有什么错,这是一种很好的学习方式,有时甚至专家也错了。但是,既然你还不是专家,你应该用你可能是错的话来表达你的评论。例如,您的第一条评论可能是“您确定这只允许JSON和EF设置属性吗?在我看来,类的成员也可以进行更改。”删除了该评论。下次评论时会更加小心