afo*_*tad 2 .net string variables int inheritance
我反汇编了.NET'System'DLL并查看了变量类(string,int,byte等)的源代码,看看我是否可以弄清楚如何创建一个可以接受值的类.我注意到"Int32"类继承了以下内容:IComparable,IFormattable,IConvertible,IComparable,IEquatable.
String和Int32类是不可继承的,我无法弄清楚这些继承的接口允许类保存值.我想要的是这样的:
public class MyVariable : //inherits here
{
//Code in here that allows it to get/set the value
}
public static class Main(string[] args)
{
MyVariable a = "This is my own custom variable!";
MyVariable b = 2976;
if(a == "Hello") { }
if(b = 10) { }
Console.WriteLine(a.ToString());
Console.WriteLine(a.ToString());
}
Run Code Online (Sandbox Code Playgroud)
假设你想要一个可以是字符串或int的类型(比如Haskell的Either):
public sealed class StringOrInt32
{
private string stringValue;
private int int32Value;
private bool isString;
public bool IsString { get { return isString; } }
public bool IsInt32 { get { return !isString; } }
public string StringValue
{
get
{
if(!isString) throw new InvalidOperationException();
return stringValue;
}
}
public int Int32Value
{
get
{
if(isString) throw new InvalidOperationException();
return int32Value;
}
}
public StringOrInt32(string value)
{
isString = true;
stringValue = value;
}
public StringOrInt32(int value)
{
isString = false;
int32Value = value;
}
// Allows writing this:
// StringOrInt32 foo = "Hello world!";
public static implicit operator StringOrInt32(string value)
{
return new MyVariable(value);
}
// Allows writing this:
// StringOrInt32 foo = 42;
public static implicit operator StringOrInt32(int value)
{
return new MyVariable(value);
}
// Allows writing this:
// StringOrInt32 foo = "Hello world!;
// string bar = (string)foo;
// Though foo.StringValue directly would be better
public static explicit operator string(StringOrInt32 value)
{
return value.StringValule;
}
// Allows writing this:
// StringOrInt32 foo = 42;
// int bar = (int)foo;
// Though foo.Int32Value directly would be better
public static explicit operator int(StringOrInt32 value)
{
return value.Int32Value;
}
public static bool operator==(StringOrInt32 left, StringOrInt32 right)
{
if(left.IsString != right.IsString)
return false;
if(left.IsString)
return left.StringValue == right.StringValue;
else
return left.Int32Value == right.Int32Value;
}
public static bool operator!=(StringOrInt32 left, StringOrInt32 right)
{
return !(left == right)
}
// Don't forget to override object.Equals(), object.GetHashCode(),
// and consider implementing IEquatable<StringOrInt32>
// Also, null checks, etc
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
511 次 |
| 最近记录: |