将值从字符串转换为 Guid 或 int 的通用类型
我有一个通用方法,它将 id 从字符串(例如,从 ASP.NET 表单上的 HiddenField 的值检索)转换为目标类型并对其执行某些操作。
private void MyMethod<T>(string rawId, Action<T> doSomethingWithId)
{
T id = (T)Convert.ChangeType(rawId, typeof(T));
doSomethingWithId(id);
}
T 将是 Guid 或 Int32,当它是 Guid 时,上面的代码会失败(在运行时),表示从 String 到 Guid 的转换无效。
然后我想我可能会尝试检查类型,如果是 Guid,则实例化一个新的 Guid:
var id = default(T);
if (id is Guid)
id = new Guid(rawId);
else
id = (T)Convert.ChangeType(rawId, typeof(T));
现在这会给出一个错误(在编译时),Guid 无法转换为类型 T
不太确定如何解决此问题。有什么建议吗?
I've got a generic method which converts an id from a string (eg, retrieved from the Value of a HiddenField on an ASP.NET Form) to a target type and does something with it.
private void MyMethod<T>(string rawId, Action<T> doSomethingWithId)
{
T id = (T)Convert.ChangeType(rawId, typeof(T));
doSomethingWithId(id);
}
T will be either Guid or Int32 and the above code falls over (at runtime) when it is Guid, saying that the cast from String to Guid is invalid.
Then I thought I might try to check the type and if Guid, instantiate a new Guid:
var id = default(T);
if (id is Guid)
id = new Guid(rawId);
else
id = (T)Convert.ChangeType(rawId, typeof(T));
now this gives an error (at compile time) that Guid cannot be converted to type T
Not too sure how to work around this. Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
下面的代码可以很好地转换为 Guid 。检查一下
the below code works fine with conversion to Guid . check it
如果
T
是Guid
或Int32
那么它就不是真的非常通用,不是吗?只需编写两个方法即可 - 要么使用不同的名称,要么可能重载。我没有看到在这里使用泛型的好处,而且它很可能会使您的代码比需要的更加复杂。If
T
will either beGuid
orInt32
then it's not really very generic, is it? Just write two methods instead - either with different names, or possibly overloads. I don't see the benefit in using generics here, and it may very well make your code more complicated than it needs to be.你也许可以尝试这样的事情:
You can try something like this perhaps: