首先我搜索了這一點,我發現對堆棧溢出以下鏈接:C#中new object()和new {}之間的區別是什麼?
- Is there any difference between `new object()` and `new {}` in c#?
- Difference between object a = new Dog() vs Dog a = new Dog()
,但我不滿意這個答案,這不是解釋得很好(我沒有得到它)。 基本上,我想知道new object()
和new {}
之間的區別。 如何在編譯時和運行時處理它們?
Secondaly,我有以下的代碼,我在我的asp.net簡單的應用程序用於WebMethods
[WebMethod]
[ScriptMethod(UseHttpGet = false)]
public static object SaveMenus(MenuManager proParams)
{
object data = new { }; // here im creating an instance of an 'object' and i have typed it `new {}` but not `new object(){}`.
try
{
MenuManager menu = new MenuManager();
menu.Name = proParams.Name;
menu.Icon = proParams.Icon;
bool status = menu.MenuSave(menu);
if (status)
{
// however, here i'm returning an anonymous type
data = new
{
status = true,
message = "Successfully Done!"
};
}
}
catch (Exception ex)
{
data = new { status = false, message = ex.Message.ToString() };
}
return data;
}
所以,(你可以在代碼註釋中看到),如何new object(){}
和new {}
差異?
這是甚至正確的方式,我寫代碼? 你能爲這段代碼提供一個最好的方法嗎?
我知道了,我不能很好地解釋它,我問很多,但這是我現在最好的。
你'新{}'是建立一個[匿名類型(http://msdn.microsoft.com/en-us/library/vstudio/bb397696 .aspx) – CodesInChaos
new {}用於匿名類型,new object()只是對象類的構造函數。 – Cybermaxs
這並不是什麼太壞的問題,我得到了'-1' –