我应该为Linq2Sql数据使用Struct而不是轻量级数据类吗? [英] Should I use a Struct instead of a lightweight data class for my Linq2Sql data?

查看:33
本文介绍了我应该为Linq2Sql数据使用Struct而不是轻量级数据类吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常采用linq2sql生成的类,并像这样创建一个简单的仅数据类.

I often take the classes that linq2sql generates and create a simple data-only class like so

public class myentity
{
     public Guid id { get; set; }
     public string name { get; set; }
     // etc
}

我不在这些类中放置方法,我主要将它们用作帮助程序类,因此我可以很容易地序列化到json和其他类似的动作/从中进行序列化.

I don't put methods in these classes and I mainly use them as helper classes so I can serialize to/from json and other similar actions, quite easily.

我的问题是,在这种情况下,我应该使用结构而不是类吗?

My question is, should I use a struct in this case rather than a class?

将它作为一个结构或多或少地定义为一个结构似乎很有意义,但是我不知道性能在这里是否理想,因为我经常在方法之间传递类,而我却不这样做.因为结构是值类型,所以不需要大量副本.

It seems to make sense to make it a struct as its more or less the definition of a struct, but I dont know if the performance will be ideal here since I often pass the classes around from method to method and I don't want a ton of copies since structs are value types.

我经常做的另一件事是使用Linq2Sql的延迟执行返回我自己的轻量级版本的Linq2Sql类,而不是它们生成的类.我不确定使用结构而不是类是否会对性能产生不利影响.

Another thing I do quite often is use Linq2Sql's delayed execution to return my own lightweight version of the Linq2Sql classes, rather than the one they generate. I'm not entirely sure if using a struct instead of a class would have some adverse performance impact here.

我将如何使用延迟执行的一个例子是这样的

an example of how I'd use delayed execution is something like this

public IEnumerable<myentity> getEntities()
{
     return from me in MyEntity return new myentity() { id = me.id, name = me.name };
}

public IEnumerable<myentity> getEntitiesThatStartWith(string s)
{
     return from me in getEntities() where me.name.StartsWith(s);
}

推荐答案

我会选择一个 class .可变的 struct 很少是一件好事.如果您没有看到使用结构而不是类的明显优势,则应避免使用它.

I'd go with a class. A mutable struct is rarely a good thing. If you don't see a clear advantage of using structs instead of classes, you should avoid it.

具体来说,在您的情况下,使用 struct 会使方法很难修改实例的内容(例如,从JSON反序列化并填充某些属性;您必须使用ref 一直).

Specifically, in your case, using a struct makes it harder for a method to modify contents of an instance (e.g. deserialize from JSON and fill some properties; you'd have to use ref all the time).

假设 Entity 是一个结构:

List<Entity> entities = ...;
entities[0].Name = "Test"; // won't compile.

这篇关于我应该为Linq2Sql数据使用Struct而不是轻量级数据类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆