using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp4
{
public struct A1 {
public int a { get; set; }
public int b { get; set; }
public int c { get; set; }
public int d { get; set; }
}
public class B1
{
public int a { get; set; }
public int b { get; set; }
public int c { get; set; }
public int d { get; set; }
}
class Program
{
static void Main(string[] args)
{
Stopwatch watch = new Stopwatch();
watch.Start();
for (int i = 0; i < 10000000; i++)
{
var A = new A1();
}
watch.Stop();
Console.WriteLine(watch.ElapsedMilliseconds);
watch = new Stopwatch();
watch.Start();
for (int i = 0; i < 10000000; i++)
{
var B = new B1();
}
watch.Stop();
Console.WriteLine(watch.ElapsedMilliseconds);
Console.Read();
}
}
}
执行结果
1. struct在栈里面,class在堆里面。
2. struct不支持继承。
3. struct 不能有参数为空的构造函数,如果提供了构造函数,必须把所有的变量全都初始化一遍
4. 不能直接初始化变量。
5. struct是值类型,class是引用类型,这是最本质区别。
6. struct轻量级,class重量级。
7. 当涉及数组操作时,struct效率高,涉及collection操作时,class效率高