将一个对象转换为 System Guid

15
Guid mainfolderid = (main.GetValue(""));

其中main是一个动态实体。

如何将上面提到的main.GetValue("")转换为System.Guid

错误信息显示:

无法隐式转换对象类型为“System.Guid”。

7个回答

27

GetValue 方法是否返回以 object 类型为标识的 Guid 值?如果是这样,你只需要执行一个显式转换即可:

Guid mainfolderid = (Guid)main.GetValue("");
如果不是这样,GetValue返回的内容是否可以被传递给其中一个构造函数(例如一个byte[]string)?如果是这样,你可以尝试这样做:
Guid mainfolderid = new Guid(main.GetValue(""));
如果以上两种情况都不适用,那么您需要手动转换通过 GetValue 返回的任何内容为 Guid

5
如果您正在使用 .Net 4.0,那么 Guid 结构中增加了解析方法:
Guid Guid.Parse(string input)

并且

bool Guid.TryParse(string input, out Guid result)

将做你想要的事情。


4
Guid mainfolderid = new Guid(main.GetValue("").ToString());

3
错误。Guid.NewGuid 不接受任何参数。 - dtb
2
如果main.GetValue("")的类型为Object,代码无法工作。Guid构造函数不接受Object作为参数。 - ChessWhiz

1
一种方法是使用GUID构造函数,并将其传递一个GUID的字符串表示形式。如果对象确实是GUID的字符串表示形式,则此方法可行。例如:
Guid mainfolderid = new Guid(main.GetValue("").ToString());

1
这个可以编译通过。但我不会称它为“傻瓜式”的。它只在非常有限的情况下才能工作。不建议使用。 - dtb

0
Guid mainfolderid = (Guid)(main.GetValue(""));

仍然显示必须使用作为引用类型或可空类型的 as 运算符(System.Guid 是非可空类型)。 - Ashutosh
@dtb,你应该已经看到了我编辑之前的那个错误。我自己注意到了 :) - Steve Danner
@Ashutosh,是的,请看我的编辑。另外,如果GetValue方法返回的是Guid的字符串表示而不是实际的Guid,则应使用Dustin的答案。 - Steve Danner

0

Guid 可以通过字符串表示法构造, 因此这应该可以工作:

Guid result = new Guid(main.GetValue("").ToString());

-1

有一个解决方案是使用对象的类型:

GuidAttribute   guidAttr;
object[]        arrAttrs;
Type            type;
string          strGuid;

type = main.GetType();
arrAttrs = type.Assembly.GetCustomAttributes(typeof(System.Runtime.InteropServices.GuidAttribute), false);
guidAttr = (arrAttrs != null && arrAttrs.Length > 0) ? arrAttrs[0] as GuidAttribute: null;
if (guidAttr != null) {
    strGuid = "{" + guidAttr.Value.ToUpper() + "}";
}

1
-1:警告:这将返回typeof(main)的GUID,而不是每个main实例的唯一GUID,也不是由main.GetValue()返回的每个值的唯一GUID。 - Kasper van den Berg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接