尝试重载从 short 到 bool 的强制转换。

huangapple go评论79阅读模式
英文:

c# attempting to overload a cast from short to bool

问题

I am attempting to overload a cast to short from a boolean. (true is 1 false is 0)

not quite sure how to go about it.
here was my attempt.

here is the fiddle
https://dotnetfiddle.net/STWWfy

using System;

public class Program
{
public static void Main()
{
MyClass myObject = new MyClass();
myObject.x = (short)false;
}
}

public class MyClass
{
public short x {get; set;}
}

public static implicit operator short(bool v)
{
return (short)(v ? 1 : 0);
}

英文:

I am attempting to overload a cast to short from a boolean. (true is 1 false is 0)

not quite sure how to go about it.
here was my attempt.

here is the fiddle
https://dotnetfiddle.net/STWWfy

using System;
					
public class Program
{
	public static void Main()
	{
		MyClass myObject = new MyClass();
		myObject.x = (short)false;
	}
}

public class MyClass
	{
	  public short x {get; set;}
    }

public static implicit operator short(bool v)
{
    return (short)(v ? 1 : 0);
}

答案1

得分: 2

有内置方法可以做到这一点,请参阅Convert类:

var x = Convert.ToInt16(true);   // x == 1
var y = Convert.ToInt16(false);  // y == 0

正如其他人所说,您不能编写自己的转换,只能针对您定义的类型。

英文:

There are built-in methods to do this, see the Convert class:

var x = Convert.ToInt16(true);   // x == 1
var y = Convert.ToInt16(false);  // y == 0

As others have said, you can't write your own conversions, only for types that you define.

huangapple
  • 本文由 发表于 2020年1月3日 21:15:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/59579253.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定