2015-07-10 75 views
0

已存在我使用下面的代码如何检查是否GetPropertyItem在C#

int OrientationId = 0x0112; 
imgd.SetPropertyItem(imgs.GetPropertyItem(OrientationId)); 

在C#中抢持有它的方向的图像多数民众赞成在propertyitem。但是,如果此propertyitem不存在它会引发以下错误“在System.Drawing.dll中发生类型'System.ArgumentException'的异常,但未在用户代码中处理”

因此,我想我需要一些方法来在运行此代码之前确定此属性项是否存在。任何帮助或输入高度赞赏,谢谢!

+0

什么'imgd'和'imgs'? –

+0

GetPropertyItem返回null是问题吗?如果是这样,你可以不把它放入一个局部变量,并在将它传递给Set之前检查它? – Chris

+1

在您的问题中添加异常提供的消息会很有用。 –

回答

0

您可以只使用一个try catch

int OrientationId = 0x0112; 
try 
{ 
    imgd.SetPropertyItem(imgs.GetPropertyItem(OrientationId)); 
} 
catch(ArgumentException e) 
{ 
    // Do whatever needs to be done 
    Console.Log(e.Message); 
} 

ArgumentException似乎在告诉你,错误不是由GetPropertyItemSetPropertyItemnull参数抛出的方式。避免的方法之一是:

int OrientationId = 0x0112; 
PropertyItem p = imgs.GetPropertyItem(OrientationId); 

if (p != null) imgd.SetPropertyItem(p); 
+1

如果找不到该属性,也会引发ArgumentException。最好查看实际存在的属性,而不是处理异常 –

+0

我认为在检查目的中使用'try catch'总是一个坏主意。看看我的答案。 –

2

假设这是一个Image,您可以使用Image.PropertyIdList和检查,如果你想的ID在该列表中存在。

喜欢的东西:

var ids = imgs.PropertyIdList; 
if (ids.IndexOf(OrientationId) != -1) 
{ 
    imgd.SetPropertyItem(imgs.GetPropertyItem(OrientationId)); 
} 
else 
{ 
    // do something else 
} 
+1

或用'PropertyItems'检索所有属性,然后复制实际需要的属性 –

1

如果您正在使用LINQ,你可以简单地做:

var propertyExists = image.PropertyItems.Any(p => p.Id == 0x0112); 

或者,如果你不想使用Linq:

var propertyFound = false; 
foreach (var prop in image.PropertyItems) 
{ 
    if (prop.Id == 0x0112) propertyFound = true; 
}