英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论