[英]How can you instantiate an object with a string and send a parameter in C#?
[英]How to send a Parameter while instantiate a field with a custom type inside a Class C#
我希望標題清楚。 我有這堂課
class PageSettings
{
public string name { get; set; }
public IDictionary<string,dynamic> settings { get; set; }
// Constructor
public PageSettings(string pageName)
{
name = pageName;
}
}
我想在另一個類中使用該類:
class AppSettings
{
public PageSettings homePageSettings { get; set; }
public PageSettings anotherPageSettings { get; set; }
}
哪個是正確的方法? 我相信這種方式是不正確的:
public PageSettings homePageSettings = new PageSettings("Home");
我想保持封裝,我只是在學習C#和正確的OOP。 我來自Javascript背景,除了prototype
之外,沒有任何類。
如果只想初始化這些屬性:
public PageSettings homePageSettings { get; set; }
public PageSettings anotherPageSettings { get; set; }
您可以在具有那些屬性的對象的構造函數中執行此操作:
public AppSettings()
{
homePageSettings = new PageSettings("someValue");
anotherPageSettings = new PageSettings("anotherValue");
}
如果要使用傳遞給AppSetting
值而不是硬編碼的值,則也可以將它們放在構造函數中:
public AppSettings(string someValue, string anotherValue)
{
homePageSettings = new PageSettings(someValue);
anotherPageSettings = new PageSettings(anotherValue);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.