0

我正在尝试在 C#中重新创建它。

我得到的问题是,如果我使用构造函数,我必须使用我不想要的 new MyInt(冗长)。解决方法是使用隐式/显式运算符。但是它们必须是公开的......我到底是如何在 C# 中实现这个功能的?

简短的问题是我想将字节/短传递给一个函数,而不是 int。传递 int 应该会给我一个编译错误。我知道我可以使用公共隐式 int 运算符轻松获得运行时。下面的代码显示int自动转换为char

运行示例显示 true

using System;
class Program
{
        public static void Write(MyInt v)
        {
                Console.WriteLine("{0}", v.v is byte);
        }
        static void Main(string[] args)
        {
                Write(2);
        }
}
public struct MyInt
{
        public object v;
        public MyInt(byte vv) { v = vv; }
        public MyInt(short vv) { v = vv; }
        public MyInt(byte[] vv) { v = vv; }
        public static implicit operator MyInt(byte vv) { return new MyInt { v = vv }; }
        //public static extern implicit operator MyInt(int vv);
}

这是更多无用的代码。它实现了 C++ 解决方案中不需要的 MyInt2/MyInt

4

1 回答 1

3

只需声明您的函数很短。Byte 将被隐式转换为 short,但没有从 int 到 short 的隐式转换,因此 int 不会通过

public class Class1
{
  public static void Aaa(short a)
  {

  }

  public void Bbb()
  {
    int i = 5;
    byte b = 1;
    short c = 1;
    Class1.Aaa(i); // Gives error
    Class1.Aaa(b); // Ok
    Class1.Aaa(c);  // ok
  }
}
于 2012-07-11T11:41:57.020 回答