如何:确定数据格式是否存在于数据对象中

更新:2007 年 11 月

下面的示例演示如何使用各种 GetDataPresent 方法重载来查询某个特定的数据格式是否存在于数据对象中。

示例

说明

下面的示例代码使用 GetDataPresent(String) 重载来按说明符字符串查询某个特定的数据格式是否存在。

代码

DataObject dataObject = new DataObject("Some string data to store...");

// Query for the presence of Text data in the data object, by a data format descriptor string.
// In this overload of GetDataPresent, the method will return true both for native data formats
// and when the data can automatically be converted to the specifed format.

// In this case, string data is present natively, so GetDataPresent returns false.
string textData = null;
if (dataObject.GetDataPresent(DataFormats.StringFormat))
{
    textData = dataObject.GetData(DataFormats.StringFormat) as string;
}

// In this case, the Text data in the data object can be autoconverted to 
// Unicode text, so GetDataPresent returns "true".
byte[] unicodeData = null;
if (dataObject.GetDataPresent(DataFormats.UnicodeText))
{
    unicodeData = dataObject.GetData(DataFormats.UnicodeText) as byte[];
}

示例

说明

下面的示例代码使用 GetDataPresent(Type) 重载来按类型查询某个特定的数据格式是否存在。

代码

DataObject dataObject = new DataObject("Some string data to store...");

// Query for the presence of String data in the data object, by type.  In this overload 
// of GetDataPresent, the method will return true both for native data formats
// and when the data can automatically be converted to the specifed format.

// In this case, the Text data present in the data object can be autoconverted
// to type string (also represented by DataFormats.String), so GetDataPresent returns "true".
string stringData = null;
if (dataObject.GetDataPresent(typeof(string)))
{
    stringData = dataObject.GetData(DataFormats.Text) as string;
}

示例

说明

下面的示例代码使用 GetDataPresent(String, Boolean) 重载来按说明符字符串查询数据,并指定如何处理可自动转换的数据格式。

代码

DataObject dataObject = new DataObject("Some string data to store...");

// Query for the presence of Text data in the data object, by data format descriptor string,
// and specifying whether auto-convertible data formats are acceptable.  

// In this case, Text data is present natively, so GetDataPresent returns "true".
string textData = null;
if (dataObject.GetDataPresent(DataFormats.Text, false /* Auto-convert? */))
{
    textData = dataObject.GetData(DataFormats.Text) as string;
}

// In this case, the Text data in the data object can be autoconverted to 
// Unicode text, but it is not available natively, so GetDataPresent returns "false".
byte[] unicodeData = null;
if (dataObject.GetDataPresent(DataFormats.UnicodeText, false /* Auto-convert? */))
{
    unicodeData = dataObject.GetData(DataFormats.UnicodeText) as byte[];
}

// In this case, the Text data in the data object can be autoconverted to 
// Unicode text, so GetDataPresent returns "true".
if (dataObject.GetDataPresent(DataFormats.UnicodeText, true /* Auto-convert? */))
{
    unicodeData = dataObject.GetData(DataFormats.UnicodeText) as byte[];
}

请参见

参考

IDataObject

其他资源

拖放示例