【问题标题】:C#: explicit typeconversion [duplicate]C#:显式类型转换
【发布时间】:2016-06-03 02:31:00
【问题描述】:

我目前正在努力寻找练习的解决方案。 如何修改 ClassA 以便第二部分中的显式类型转换成为可能?

class ClassA {
public int MyValue = 0;
public string MyText = "Hello World!";

//Code to impl
}

ClassA myObject = new ClassA();
myObject.MyValue = 42;
myObject.MyText = "Hi!"
int x = (int)myObject;
string str = (string)myObject;

【问题讨论】:

标签: c#


【解决方案1】:

ClassA 定义中的类似内容应该可以工作:

public static explicit operator int(ClassA a)
{
    return a.MyValue;
}

public static explicit operator string(ClassA a)
{
    return a.MyText;
}

(我实际上不记得这种情况是否需要implicitexplicit,目前无法对其进行测试。根据您的需要,这两个都值得测试。)

虽然你为什么要这样做有点奇怪,而不是直接获取这些公共值:

int x = myObject.MyValue;
string str = myObject.MyText;

【讨论】:

  • 谢谢你,我错过了
  • @David 不知道你为什么编辑你的答案; OP 要求 explicit 转换,所以原来的解决方案很好。
  • @poke:实际上,我在两者之间摇摆不定。我已经 很长时间 这样做了,所以我不确定是哪个。
【解决方案2】:

您定义一个显式转换。

这里的诀窍是 EXPLICIT 键。

https://msdn.microsoft.com/en-us/library/xhbhezf4.aspx

有这样的例子。

基本上:类必须在 for like 中实现一个有状态的显式操作符...

// Must be defined inside a class called Fahrenheit:
public static explicit operator Celsius(Fahrenheit fahr)
{
    return new Celsius((5.0f / 9.0f) * (fahr.degrees - 32));
}

【讨论】:

    猜你喜欢
    • 2011-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-14
    • 2016-11-24
    • 1970-01-01
    • 2012-02-15
    相关资源
    最近更新 更多