[英]How to access the instance variable value from the diffrrent class in C#
創建具有屬性a1的類
class A
{
public int a1 { get; set; }
}
在B中為A類創建對象並為其分配值
class B
{
A a=new A();
a.a1=45;
}
如何在不同的類中獲取分配的值。
class C
{
//How to access the 45 value from the class B instance variable here
//without using static keyword.
}
你可以嘗試
class A
{
public int a1 { get; set; }
}
class B
{
public A a = new A();
public B()
{
a.a1 = 45; //you need to put that in a method..
}
}
class C
{
B b = new B(); // instance of B in C
int aValue = b.a.a1; // access b's instance of A
}
更好的解決方案:
class A
{
public int a1 { get; set; }
}
class B
{
A a = new A();
public int A_Value
{
get { return a.a1; }
set { a.a1 = value; }
}
}
class C
{
B b = new B(); // instance of B in C
public C()
{
b.A_Value = 45;
}
}
在方法或構造函數中接受A或B作為參數。 在以下情況下,A和B是可互換的。
public class C
{
A _a;
public C(A a)
{
_a = a;
}
void Do() // Using constructor parameter.
{
Console.WriteLine(_a.a1); // Should print 45, so long as your other code has already ran.
}
void Do(B b) // Using method parameter.
{
Console.WriteLine(b.A.a1); // will write 45
}
}
尊敬的是,這些答案似乎使水變得渾濁。 這里冒着喂巨魔的風險,因為這個問題似乎沒有實際應用,我將提出建議。 除了一些基本約定外,我還為每個類添加了公共構造函數,為存儲在B中的A實例應用了公共獲取器,然后在C上提供了一個方法,該方法從A中的實例返回“ A1”屬性。 B的實例。寫完最后一句話就標明了這項任務的復雜程度。
public class A
{
public A() { }
public int A1 { get; set; }
}
public class B
{
public B()
{
this._a = new A() { A1 = 42 };
}
private A _a;
public A A
{
get { return _a; }
}
}
public class C
{
public C() { }
public int GetA1FromA()
{
return new B().A.A1;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.