C#中的`new object()`和`new {}`有什么区别? [英] What is the Difference Between `new object()` and `new {}` in C#?
问题描述
首先,我对此进行了搜索,并在堆栈溢出中找到了以下链接:
First of all i searched on this and i found the following links on 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 {}
之间的区别。 如何在编译时和运行时对它们进行处理?
But i'm not satisfied with this answer, it's not explained well (i didn't get it well).
Basically, i want to know the difference between new object()
and new {}
. How, they are treated at compile time and runtime?
Secondaly,我有以下代码用于 WebMethods
Secondaly, i have the following code which i have used for WebMethods
in my asp.net simple application
[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 {}
的区别?
So, (as you can see in comments in code), How new object(){}
and new {}
differences?
这是我编写代码的正确方法吗?
您能建议使用此代码的最佳方法吗?
我知道,我不能很好地解释它,我在问很多,但这是我目前拥有的最好的。
I know, i can't explain it well and i'm asking alot, but that's the best i have right now.
推荐答案
new {...}
始终创建匿名对象,例如:
Object sample = new {};
String sampleName = sample.GetType().Name; // <- something like "<>f__AnonymousType0"
// not "Object"
同时 new Object()
创建 Object
类的实例
Object sample = new Object() {};
String sampleName = sample.GetType().Name; // <- "Object"
因为所有对象(包括匿名对象)均源自对象
,您随时可以输入
since all objects (including anonymous ones) are derived from Object
you can always type
Object sample = new {};
这篇关于C#中的`new object()`和`new {}`有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!