When should I use a struct instead of a class?

后端 未结 15 2284
臣服心动
臣服心动 2020-11-22 13:00

MSDN says that you should use structs when you need lightweight objects. Are there any other scenarios when a struct is preferable over a class?

Some people might ha

15条回答
  •  Happy的楠姐
    2020-11-22 13:31

    Bill Wagner has a chapter about this in his book "effective c#" (http://www.amazon.com/Effective-Specific-Ways-Improve-Your/dp/0321245660). He concludes by using the following principle:

    1. Is the main responsability of the type data storage?
    2. Is its public interface defined entirely by properties that access or modify its data members?
    3. Are you sure your type will never have subclasses?
    4. Are you sure your type will never be treated polymorphically?

    If you answer 'yes' to all 4 questions: use a struct. Otherwise, use a class.

提交回复
热议问题