English 中文(简体)
InvalidCastException in (int)(targetInstance.GetPropertyValue (“EventCode”);
原标题:InvalidCastException in (int)(targetInstance.GetPropertyValue("EventCode"));
  • 时间:2012-01-13 12:01:02
  •  标签:
  • c#
  • casting

我试图获得《事件法》的价值(这是一股):

private static void EventLogMonitor(object sender, EventArrivedEventArgs e)
{
  ManagementBaseObject targetInstance = (ManagementBaseObject)e.NewEvent.GetPropertyValue("TargetInstance");
  EventId = (int)(targetInstance.GetPropertyValue("EventCode"));
  ...

但是,在<代码>(int)(目标设计.GetPropertyValue (“EventCode”)上,我获得了一个无效的例外。 似乎这部法典是个目标,我想知道,如何利用《事件守则》的价值?

最佳回答

Assuming that you are dealing with Win32_NTLogEvent classes, you need to cast to UInt16 (or ushort), as that is the type for "EventCode" according to msdn.

(UInt16)(targetInstance.GetPropertyValue("EventCode"))
问题回答

您应投身于未签署,而不是隐蔽。

(uint)(targetInstance.GetPropertyValue("EventCode"))

http://www.ohchr.org。 箱式价值(即通过object)要求知道财产的确切类型,包括如果财产无效或无效的话。 呼吁

targetInstance.GetPropertyValue("EventCode").GetType().FullNa‌​me

请你找到确切的类型。

提 出

Convert.ToUInt32(targetInstance.GetPropertyValue("EventCode"))

<代码>targetInstance.GetPropertyValue (“EventCode”) 回归箱式ushort

将一个箱子(ushort<>/code>改为ushort的有效插图:

ushort usVal = (ushort)boxUS;

将<代码>ushort改为int的有效明确表述如下:

int iVal = (int)ushortVal;

将<代码>ushort改为int的有效默示表述如下:

int iVal = uShortVal;

但是,将一个盒式的<代码>ushort<>/code>改为int没有有效的默示或明确表述:

int iVal = (int)boxUS; // throws exception.

但是,我们可以把上述内容结合起来:

int iVal = (int)(ushort)boxUS;
int iVal2 = (ushort)boxUS;

因此:

EventID = (ushort)targetInstance.GetPropertyValue("EventCode"); //works
EventID = (int)(ushort)targetInstance.GetPropertyValue("EventCode"); //works and arguably clearer.

我们还可以使用<代码>Convert的类别,即价格更昂贵、价格更快的类别,但在有几种可能的盒式价值的情况下,则使用手法。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签