【发布时间】:2021-05-10 14:40:25
【问题描述】:
首先我对此进行了搜索,并在 Stack Overflow 上找到了以下链接:
- 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 {} 之间的区别。 如何在编译时和运行时处理它们?
其次,我在我的 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;
}
那么,(正如您在代码中的 cmets 中看到的那样),new object(){} 和 new {} 有何区别?
这甚至是我编写代码的正确方式吗? 您能否建议此代码的最佳方法?
我知道,我不能很好地解释它,我问了很多,但这是我现在最好的。
【问题讨论】:
-
您的
new{}正在创建一个anonymous type -
new {} 用于匿名类型,new object() 只是对象类的构造函数。
-
我得到
-1的问题并不是那么糟糕 -
@Cybermaxs-Betclic,我知道结果类型是对象的匿名类型,但
MSIL如何处理它们?这会由 c# 编译器生成一个新的Anonymouse类型的单独代码吗? -
这对我来说是新信息。我可以使用
new {}为所有对象类型创建实例吗?