隐式和显式转换
问题描述:
这是可能的吗?隐式和显式转换
string wellFormattedGuidAsString = ...;
Guid guid = wellFormattedGuidAsString;
...
Method(wellFormattedGuidAsString);
void Method(Guid id) { ... }
我试着用显式和隐式转换。
public static implicit operator Guid(string str)
{
Guid guid;
Guid.TryParse(str, out guid);
return guid;
}
答
您不能在所需对象之外创建隐式和显式运算符。
你可以做的反而是:
public static class StringEx
{
public static Guid ToGuid(this string str)
{
Guid guid;
Guid.TryParse(str, out guid);
return guid;
}
}
而且以后你可以使用它像:
string mestring = " ... ";
Guid guid = mestring.ToGuid();
编辑:
还有另外一种方式(当然有)这是有点无用,但我会张贴在这里:
做一个类,将包裹string
public class StringWrapper
{
string _string;
public StringWrapper(string str)
{
_string = str;
}
public static implicit StringWrapper operator(string str)
{
return new StringWrapper(str);
}
public static implicit string operator(StringWrapper strWrapper)
{
return strWrapper._string;
}
public static implicit Guid operator(StringWrapper strWrapper)
{
Guid guid;
Guid.TryParse(str, out guid);
return guid;
}
public static implicit StringWrapper operator(Guid guid)
{
return guid.ToString();
}
}
这没用类咱们你做这样的事情:
string str = "..";
Guid guid = (StringWrapper)str;
答
只是超载你的方法:
void Method(Guid id) { ... }
void Method(string guid) {
Guid _guid;
Guid.TryParse(guid, out _guid);
Method(_guid);
}
发生了什么事,当你尝试它? –
你试过了......发生了什么? –
您不能为现有.net类型重载运算符,您可以提供一个将'string'转换为'Guid'的扩展方法。 –