我想知道是否有人可以想到一个很好的解决方法,因为无法在自己的类上为对象添加隐式强制转换操作符.以下示例说明了我想要的代码类型
public class Response
{
public string Contents { get; set; }
public static implicit operator Response(object source)
{
return new Response { Contents = source.ToString(); };
}
}
Run Code Online (Sandbox Code Playgroud)
这将无法编译,因为它扰乱了C#编译器,它告诉我
user-defined conversions to or from a base class are not allowed
Run Code Online (Sandbox Code Playgroud)
将响应转化为响应和行动
public static implicit operator Response<T>(T source)
Run Code Online (Sandbox Code Playgroud)
遗憾的是不是一种选择.我的猜测是否定的,但任何人都可以想到一个很好的解决方法/黑客来实现这一点.我很乐意能够做到
public Response Foo()
{
return new Bar();
}
Run Code Online (Sandbox Code Playgroud)
最后得到一个表示Whatever.Namespace.Bar的Response.Contents
假设您有自己的类如下:
public sealed class StringToInt {
private string _myString;
private StringToInt(string value)
{
_myString = value;
} public static implicit operator int(StringToInt obj)
{
return Convert.ToInt32(obj._myString);
}
public static implicit operator string(StringToInt obj)
{
return obj._myString;
}
public static implicit operator StringToInt(string obj)
{
return new StringToInt(obj);
}
public static implicit operator StringToInt(int obj)
{
return new StringToInt(obj.ToString());
}
}
Run Code Online (Sandbox Code Playgroud)
那么您是否可以编写如下代码:
MyClass.SomeMethodThatOnlyTakesAnInt(aString);
Run Code Online (Sandbox Code Playgroud)
没有它声明没有从字符串到int的隐式转换?
[是的,我可以亲自测试一下,但我想我会把它放在那里,看看所有大师们都要说的话]