2017-07-25 52 views
0

我在我的項目中的兩個類,如下面這樣:如何訪問類的成員從頁面加載類在C#

//Class A 
public class CarHelper 
{ 
    public class Car 
    { 
     public string Colour {get;set;} 
     public string Manufacturer {get;set;} 
    } 

    public Car GetDetails() 
    { 
     Car c = new Car(); 
     var query = //querying from db here 
     c.Colour = query.Colour; 
     c.Manufacturer= query.Manufaturer; 
     return c; 
    } 
} 

//Class B 
//here i have a page load method like this: 

protected void Page_Load(object sender, EventArgs e) 
{ 
    CarHelper car = new CarHelper(); 
    var getCarManufacturer = car.Manufacturer; //<< stuck here 
    //how would I get the car manufacturer here above? 
} 

正如你可以在上面看到,最新最好的方法,從類訪問成員一個?

+5

在頁面/表單類中創建一個字段或屬性,並將值或引用存儲到'car'。我強烈建議你拿起一本c#書或教程。我也建議不要在'CarHelper'中嵌套'Car'' – Igor

回答

1

既然你已經創建GetDetails()方法是public你可以用它來讀取,像這樣Car對象值:

CarHelper carHelper = new CarHelper(); 
Car car = carHelper.GetDetails(); 
var carManufacturer = car.Manufacturer; 
+0

非常感謝您的先生 – 1future

2

Car正在CarHelper類嵌套類,因此需要既然你沒有初始化對象的car.Manufacturer最終會被null作爲默認初始化使用完全合格的名稱不同的方式像

CarHelper.Car car = new CarHelper.Car(); 
var getCarManufacturer = car.Manufacturer; 

爲引用類型