开发者

Convert an object to System Guid

开发者 https://www.devze.com 2023-01-17 15:05 出处:网络
Guid mainfolderid = (main.GetValue(\"\")); where main is a dynamic entity. How can I convert the above mentioned main.GetValue(\"\") to System.Guid?
Guid mainfolderid = (main.GetValue(""));

where main is a dynamic entity.

How can I convert the above mentioned main.GetValue("") to System.Guid?

The error says

Cannot implicitly convert type object to 'System.Guid'.开发者_JAVA百科


Does the GetValue method actually return a Guid typed as object? If so, then you just need to perform an explicit cast like so:

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

If not, does GetValue return something that can be passed to one of the constructors (ie, a byte[] or string)? In that case you could do this:

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

If neither of the above are applicable then you're going to need to do some manual work to convert whatever's returned by GetValue to a Guid.


If you're using .Net 4.0, there were Parsing methods added to the Guid struct:

Guid Guid.Parse(string input)

and

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

will do what you want.


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


One way is to use the GUID constructor, and pass it a string representation of the GUID. This will work if the object is really a string representation of GUID. Example:

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


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


Guid could be constructed by string representation, so this should work:

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


There are a solution using the Type of the objet:

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() + "}";
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号