在C#中值类型的类定义? [英] Value type class definition in C#?

查看:98
本文介绍了在C#中值类型的类定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能使一个类不是一个结构,但是值类型,或者就像是在被传递,而不是通过引用传递,它复制值类型。

Is it possible to make a class that is not a struct but is a value type, or is like a value type in that it copies on being passed instead of being passed by reference.

编辑:

抱歉有被要求后,要编辑的问题。

Sorry about the question having to be edited after being asked.

此外,更多信息请参见该问题。在结构布局
周期不存在

Also, see this question for more information. Cycle in the struct layout that doesn't exist

推荐答案

编辑2

由于现在看来,你要找使用关键字,这是由定义不可能宣告真实值类型。

As it now seems, you're looking to declare a true value type using the class keyword, which is by definition not possible.

既然你正在寻找创造类似于System.String语义的一类,你应该编译System.String。很多它的魔力在CLR隐藏起来,但大部分看看会帮助的。

Since you're looking at creating a class with semantics similar to System.String, you should probably decompile System.String. A lot of its magic is hidden away in the CLR, but much of what you will see will help.

对于初学者来说,你一定会需要重载 == != ,并覆盖等于()的GetHashCode()。你几乎肯定要实施 IComparable的< T> IEquatable< T> 以及

For starters, you'll definitely need to overload == and !=, and override Equals() and GetHashCode(). You'll almost certainly want to implement IComparable<T> and IEquatable<T> as well.

的字符串的另一个重要方面是,它们的不可改变的。这是他们的价值样行为的重要组成部分,因为它保证两个相等的字符串将始终相等。如果字符串是可变的,这将是可能的修改字符串以使其不等于其他中的一个。

Another important aspect of strings is that they are immutable. This is an important part of their value-like behavior, because it guarantees that two equal strings will always be equal. If strings were mutable, it would be possible to modify one of the strings to make it unequal to the other.

我也应该指出,虽然串具有语义,使它看起来像一个值类型,的这当然是一个引用类型的,并引用传递的某些方面是不可避免的。

I should also point out that while string has semantics that make it seem like a value type, it is of course a reference type, and some aspects of reference semantics are unavoidable.

如果您发布稍微介绍一下你为什么要做到这一点,我们可以提供更具体的建议。

If you post a little more about why you want to do this, we can offer more specific advice.

修改

在回答您的编辑,看来你有一个关于字符串的误解。虽然他们确实表现得像在某些方面的价值类型,的他们不直接由他们传递给方法每次复制他们的数据通过。的实现这一点的唯一方法是声明一个结构。串,像所有的类,是只能通过引用访问引用类型;你只可以直接操作参考;你只能通过的参考的一种方法。

In response to your edit, it seems you have a misconception about strings. While they do behave like value types in some ways, they are not passed directly by copying their data each time they are passed to a method. The only way to achieve that is to declare a struct. Strings, like all classes, are reference types that can be accessed only by reference; you can only manipulate the reference directly; you can only pass the reference to a method.

这篇关于在C#中值类型的类定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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