我有一个class Program
,其对象为class c2
,如下例所示
class c2{
public string Name;
public int RollNo;
public c2(string Name , int RollNo){
this.Name = Name;
this.RollNo = RollNo;
}
private c2 obj1;
public c2 obj{
get
{
return obj1;
}
set{
obj1=value;
}
}
public void show(){
Console.WriteLine(""+obj1.Name+" "+obj1.RollNo);
}
}
public class Program
{
public static void Main(string[] args)
{
//Your code goes here
c2 objNew = new c2("Test",12);
objNew.obj = objNew;
objNew.show();
}
}
输出:
测试12
在上面的代码中class c2
有一个私人引用obj1
,get
set
来自class program
的对象obj。如何赋值给obj和obj1因为它们没有实际存在,因为在new
运算符的帮助下,内存未分配给它们。
答案 0 :(得分:1)
是的,你可以,例如
class C1{
public C2 Obj {get;set;}
}
class C2{}
public class Program
{
public static void Main()
{
C1 c1 = new C1();
C2 prop1 = c1.Obj;
c1.Obj = new C2();
}
}
答案 1 :(得分:0)
如果以这种方式声明它们,则可以获取或设置它们。
Readonly属性:public C2 obj {get;}
撰写和阅读属性public C2 obj {get;set;}
你也可以使用public C2 obj {get;private set;}
这样的属性来做事,或者在setter方法中添加自定义验证逻辑。
您在oleksii的回答
中设置了一个属性示例答案 2 :(得分:0)
是的,你可以喜欢这个
class Car
{
public string Name { get; set; }
public Color Color { get; set; }
public CarManufacturer Manufacturer { get; set; }
}
Car car = new Car();
car.Name = "Corvette";
car.Color = Color.Yellow;
car.Manufacturer = new CarManufacturer();
car.Manufacturer.Name = "Chevrolet";
car.Manufacturer.Country = "USA";
你也可以像这样使用它
Car car = new Car {
Name = "Chevrolet Corvette",
Color = Color.Yellow,
Manufacturer = new CarManufacturer {
Name = "Chevrolet",
Country = "USA"
}
};