这可能听起来很愚蠢.我们知道我们可以为字符串变量赋值如下.
String name = "myname";
String是引用类型,但new在声明和赋值时不需要运算符.如果我想设计一个具有这种行为的自定义类,我将如何进行?
谢谢
您正在寻找的是隐式类型转换方法(Microsoft文档).举个例子,假设你有一个名为'PositiveFloat'的类自动将浮点数绑定到值> = 0,那么你可以使用以下类布局:
class PositiveFloat
{
public float val = 0.0f;
public PositiveFloat(float f)
{
val = Math.Max(f, 0.0f); //Make sure f is positive
}
//Implicitly convert float to PositiveFloat
public static implicit operator PositiveFloat(float f)
{
return new PositiveFloat(f);
}
//Implicitly convert PositiveFloat back to a normal float
public static implicit operator float(PositiveFloat pf)
{
return pf.val;
}
}
//Usage
PositiveFloat posF = 5.0f; //posF.val == 5.0f
float fl = posF; //Converts posF back to float. fl == 5.0f
posF = -15.0f; //posF.val == 0.0f - Clamped by the constructor
fl = posF; //fl == 0.0f
Run Code Online (Sandbox Code Playgroud)
在这个例子中,你也可能会想为提供隐含的操作方法+,-等支持浮动,并在此类int算术.
运算符不仅限于像int这样的核心数据类型,你可以通过使用'='隐式地从另一个类创建一个类,但是这需要开始判断上下文.是否Thing t = y;有意义,还是应Thing t = new Thing(y);,甚至Thing t = y.ConvertToThing();?随你(由你决定.
在C#的核心,基本数据类型如int,float,char等在编译器级别实现,因此我们有一些基础可以使用.字符串也是如此,即使它看起来像引用类型.这些类型如何与运算符之类的东西一起使用实际上与上面的隐式运算符相同,但是为了确保一致性,以及允许您完全用C#创建自己的"基本"类型.