How to set a value from another class

纵饮孤独 提交于 2021-02-19 03:33:10

问题


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;
   }
}

What are the other alternatives?


回答1:


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.

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




回答2:


You can use a public setter and a private getter, in case you need to access the variable in its own class.

class B {
   public int test { private get; set; }
}



回答3:


Who said a property should not use only set accessor? I don't see a design flaw in it. If there is one, I will be glad to learn something new:)




回答4:


you mean something like this?

   public int Test { get; set; }



回答5:


Your example does not really make much sense since you are not holding on to your instance of B, but you can do something like this:

class A 
{
    private B b;

    public A()
    {
        this.b = new B();
    }

    public void SetValue() 
    { 
        this.b.Test = 10;
    } 
} 

class B 
{ 
   int test; 
   public int Test
   {
       get{ return this.test; }
       set{ this.test = value; }
   }    
} 

Another alternative is to make the Test property an autoproperty (where the framework generates the backing field), like so:

class B 
{ 
   public int Test{get; set;}
} 


来源:https://stackoverflow.com/questions/2816935/how-to-set-a-value-from-another-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!