如何设置另一个类的值 [英] How to set a value from another class
问题描述
它表示属性不应仅是设置"(代码分析规则CA1044),还应该是获取".如果我需要为其他类的变量设置值,该怎么办?
Its said that property should not be "Set" only (Code analysis rule CA1044 )and it should be "Get" as well. What should i do if I need to set value to a variable from some other class?
它将不断变化,所以我无法通过构造函数传递它.
The will keep changing so I cannot pass it through constructor.
我是否应该为此创建一个函数,如下所示?
Shall I create a function for this as shown below?
class A
{
public void SetValue()
{
b = new B();
b.SetTest(10);
}
}
class B
{
int test;
public void SetTest(int value)
{
test = value;
}
}
还有哪些其他选择?
推荐答案
我同意它与只写属性(从类的观点来看)有点混淆,所以我尽量避免使用它们,并且而是创建某种set方法.
I'd agree with that it's a bit confusing with write only properties (from a client of the class points of view), so I try to avoid them and instead create a set method of some kind.
Microsoft推荐的方法似乎也是将其重写为一种方法(或在合适的情况下使其可读写):
The way recommended by Microsoft also seems to be to rewrite it to a method (or make it read and write if suitable): http://msdn.microsoft.com/en-us/library/ms182165.aspx
这篇关于如何设置另一个类的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!