本文整理匯總了C#中System.ComponentModel.TypeConverter.CanConvertFrom方法的典型用法代碼示例。如果您正苦於以下問題:C# TypeConverter.CanConvertFrom方法的具體用法?C# TypeConverter.CanConvertFrom怎麽用?C# TypeConverter.CanConvertFrom使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類System.ComponentModel.TypeConverter
的用法示例。
在下文中一共展示了TypeConverter.CanConvertFrom方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。
示例1: CheckConvert
public void CheckConvert(int expect_from, int expect_to, TypeConverter conv, Type type) {
int from_count = 0;
int to_count = 0;
foreach (Type t in typeof(int).Assembly.GetTypes ()) {
if (conv.CanConvertFrom(null, t)) {
from_count++;
if (debug > 0) {
Console.WriteLine("{0}: Conversion from {1} supported", conv.ToString(), t.ToString());
}
}
if (conv.CanConvertTo(null, t)) {
to_count++;
if (debug > 0) {
Console.WriteLine("{0}: Conversion to {1} supported", conv.ToString(), t.ToString());
}
}
}
#if not
foreach (Type t in type.Assembly.GetTypes ()) {
if (conv.CanConvertFrom(null, t)) {
from_count++;
if (debug > 0) {
Console.WriteLine("{0}: Conversion from {1} supported", conv.ToString(), t.ToString());
}
}
if (conv.CanConvertTo(null, t)) {
to_count++;
if (debug > 0) {
Console.WriteLine("{0}: Conversion to {1} supported", conv.ToString(), t.ToString());
}
}
}
#endif
if (from_count != expect_from) {
if (verbose > 0) {
Console.WriteLine("{0}: ConvertFrom expected {1}, returned {2}", conv.ToString(), expect_from, from_count);
}
failed++;
}
if (to_count != expect_to) {
if (verbose > 0) {
Console.WriteLine("{0}: ConvertTo expected {1}, returned {2}", conv.ToString(), expect_to, to_count);
}
failed++;
}
}
示例2: CDSAttributesRetrieve
/// <summary>
/// This method retrieves a set of CDSAttribute from a class.
/// </summary>
/// <param name="data">The class to examine.</param>
/// <param name="conv">A converter function to turn the value in to a string.</param>
/// <returns>Returns an enumerable collection of attributes and values.</returns>
public static IEnumerable<KeyValuePair<CDSAttributeAttribute, string>> CDSAttributesRetrieve(
this IXimuraContent data, TypeConverter conv)
{
List<KeyValuePair<PropertyInfo, CDSAttributeAttribute>> attrList =
AH.GetPropertyAttributes<CDSAttributeAttribute>(data.GetType());
foreach (KeyValuePair<PropertyInfo, CDSAttributeAttribute> reference in attrList)
{
PropertyInfo pi = reference.Key;
if (pi.PropertyType == typeof(string))
{
yield return new KeyValuePair<CDSAttributeAttribute, string>(
reference.Value, pi.GetValue(data, null) as string);
}
else if (pi.PropertyType == typeof(IEnumerable<string>))
{
IEnumerable<string> enumerator = pi.GetValue(data, null) as IEnumerable<string>;
foreach (string value in enumerator)
yield return new KeyValuePair<CDSAttributeAttribute, string>(
reference.Value, value);
}
else if (conv != null && conv.CanConvertFrom(pi.PropertyType))
{
yield return new KeyValuePair<CDSAttributeAttribute, string>(
reference.Value, conv.ConvertToString(pi.GetValue(data, null)));
}
}
}
示例3: SetValueFromConverter
private void SetValueFromConverter(string newValue, Type targetType, TypeConverter converter)
{
if (!converter.CanConvertFrom(targetType) && string.IsNullOrEmpty(newValue))
{
this.Value = null;
}
else
{
this.Value = converter.ConvertFrom(newValue);
}
}
示例4: FormatObjectInternal
/// <devdoc>
///
/// Converts a value into a format suitable for display to the end user.
///
/// - Converts DBNull or null into a suitable formatted representation of 'null'
/// - Performs some special-case conversions (eg. Boolean to CheckState)
/// - Uses TypeConverters or IConvertible where appropriate
/// - Throws a FormatException is no suitable conversion can be found
///
/// </devdoc>
private static object FormatObjectInternal(object value,
Type targetType,
TypeConverter sourceConverter,
TypeConverter targetConverter,
string formatString,
IFormatProvider formatInfo,
object formattedNullValue) {
if (value == System.DBNull.Value || value == null) {
//
// Convert DBNull to the formatted representation of 'null' (if possible)
//
if (formattedNullValue != null)
{
return formattedNullValue;
}
//
// Convert DBNull or null to a specific 'known' representation of null (otherwise fail)
//
if (targetType == stringType)
{
return String.Empty;
}
if (targetType == checkStateType) {
return CheckState.Indeterminate;
}
// Just pass null through: if this is a value type, it's been unwrapped here, so we return null
// and the caller has to wrap if appropriate.
return null;
}
//
// Special case conversions
//
if (targetType == stringType) {
if (value is IFormattable && !String.IsNullOrEmpty(formatString)) {
return (value as IFormattable).ToString(formatString, formatInfo);
}
}
//The converters for properties should take precedence. Unfortunately, we don't know whether we have one. Check vs. the
//type's TypeConverter. We're punting the case where the property-provided converter is the same as the type's converter.
Type sourceType = value.GetType();
TypeConverter sourceTypeTypeConverter = TypeDescriptor.GetConverter(sourceType);
if (sourceConverter != null && sourceConverter != sourceTypeTypeConverter && sourceConverter.CanConvertTo(targetType)) {
return sourceConverter.ConvertTo(null, GetFormatterCulture(formatInfo), value, targetType);
}
TypeConverter targetTypeTypeConverter = TypeDescriptor.GetConverter(targetType);
if (targetConverter != null && targetConverter != targetTypeTypeConverter && targetConverter.CanConvertFrom(sourceType)) {
return targetConverter.ConvertFrom(null, GetFormatterCulture(formatInfo), value);
}
if (targetType == checkStateType) {
if (sourceType == booleanType) {
return ((bool)value) ? CheckState.Checked : CheckState.Unchecked;
}
else {
if (sourceConverter == null) {
sourceConverter = sourceTypeTypeConverter;
}
if (sourceConverter != null && sourceConverter.CanConvertTo(booleanType)) {
return (bool)sourceConverter.ConvertTo(null, GetFormatterCulture(formatInfo), value, booleanType)
? CheckState.Checked : CheckState.Unchecked;
}
}
}
if (targetType.IsAssignableFrom(sourceType)) {
return value;
}
//
// If explicit type converters not provided, supply default ones instead
//
if (sourceConverter == null) {
sourceConverter = sourceTypeTypeConverter;
}
if (targetConverter == null) {
targetConverter = targetTypeTypeConverter;
}
//
// Standardized conversions
//
//.........這裏部分代碼省略.........
示例5: ParseObjectInternal
/// <devdoc>
///
/// Converts a value entered by the end user (through UI) into the corresponding binary value.
///
/// - Converts formatted representations of 'null' into DBNull
/// - Performs some special-case conversions (eg. CheckState to Boolean)
/// - Uses TypeConverters or IConvertible where appropriate
/// - Throws a FormatException is no suitable conversion can be found
///
/// </devdoc>
private static object ParseObjectInternal(object value,
Type targetType,
Type sourceType,
TypeConverter targetConverter,
TypeConverter sourceConverter,
IFormatProvider formatInfo,
object formattedNullValue) {
//
// Convert the formatted representation of 'null' to DBNull (if possible)
//
if (EqualsFormattedNullValue(value, formattedNullValue, formatInfo) || value == System.DBNull.Value) {
return System.DBNull.Value;
}
//
// Special case conversions
//
TypeConverter targetTypeTypeConverter = TypeDescriptor.GetConverter(targetType);
if (targetConverter != null && targetTypeTypeConverter != targetConverter && targetConverter.CanConvertFrom(sourceType)) {
return targetConverter.ConvertFrom(null, GetFormatterCulture(formatInfo), value);
}
TypeConverter sourceTypeTypeConverter = TypeDescriptor.GetConverter(sourceType);
if (sourceConverter != null && sourceTypeTypeConverter != sourceConverter && sourceConverter.CanConvertTo(targetType)) {
return sourceConverter.ConvertTo(null, GetFormatterCulture(formatInfo), value, targetType);
}
if (value is string) {
// If target type has a suitable Parse method, use that to parse strings
object parseResult = InvokeStringParseMethod(value, targetType, formatInfo);
if (parseResult != parseMethodNotFound) {
return parseResult;
}
}
else if (value is CheckState) {
CheckState state = (CheckState)value;
if (state == CheckState.Indeterminate) {
return DBNull.Value;
}
// Explicit conversion from CheckState to Boolean
if (targetType == booleanType) {
return (state == CheckState.Checked);
}
if (targetConverter == null) {
targetConverter = targetTypeTypeConverter;
}
if (targetConverter != null && targetConverter.CanConvertFrom(booleanType)) {
return targetConverter.ConvertFrom(null, GetFormatterCulture(formatInfo), state == CheckState.Checked);
}
}
else if (value != null && targetType.IsAssignableFrom(value.GetType())) {
// If value is already of a compatible type, just go ahead and use it
return value;
}
//
// If explicit type converters not provided, supply default ones instead
//
if (targetConverter == null) {
targetConverter = targetTypeTypeConverter;
}
if (sourceConverter == null) {
sourceConverter = sourceTypeTypeConverter;
}
//
// Standardized conversions
//
if (targetConverter != null && targetConverter.CanConvertFrom(sourceType)) {
return targetConverter.ConvertFrom(null, GetFormatterCulture(formatInfo), value);
}
else if (sourceConverter != null && sourceConverter.CanConvertTo(targetType)) {
return sourceConverter.ConvertTo(null, GetFormatterCulture(formatInfo), value, targetType);
}
else if (value is IConvertible) {
return ChangeType(value, targetType, formatInfo);
}
//
// Fail if no suitable conversion found
//
throw new FormatException(GetCantConvertMessage(value, targetType));
}
示例6: CanConvertToFrom
internal static bool CanConvertToFrom(TypeConverter converter, Type type) {
return (converter != null && converter.CanConvertTo(type) &&
converter.CanConvertFrom(type) && !(converter is ReferenceConverter));
}
示例7: SafeCanConvertFrom
bool SafeCanConvertFrom (Type type, TypeConverter cvt)
{
try {
return cvt.CanConvertFrom (type);
} catch (NotImplementedException) {
return false;
}
}
示例8: ConvertData
object ConvertData (TypeConverter c)
{
if (mime_type == ResXResourceWriter.ByteArraySerializedObjectMimeType) {
if (c.CanConvertFrom (typeof (byte [])))
return c.ConvertFrom (Convert.FromBase64String (dataString));
} else if (String.IsNullOrEmpty (mime_type)) {
if (c.CanConvertFrom (typeof (string)))
return c.ConvertFromInvariantString (dataString);
}
else
throw new Exception ("shouldnt get here, invalid mime type");
throw new TypeLoadException ("No converter for this type found");
}
示例9: CDSReferencesRetrieve
/// <summary>
/// This method retrieves a set of reference attributes from a class.
/// </summary>
/// <param name="data">The class to examine.</param>
/// <param name="conv">A converter function to turn the value in to a string.</param>
/// <returns>Returns an enumerable collection of attributes and values.</returns>
public static IEnumerable<KeyValuePair<CDSReferenceAttribute, string>> CDSReferencesRetrieve(
this IXimuraContent data, TypeConverter conv)
{
List<KeyValuePair<PropertyInfo, CDSReferenceAttribute>> attrList =
AH.GetPropertyAttributes<CDSReferenceAttribute>(data.GetType());
foreach (KeyValuePair<PropertyInfo, CDSReferenceAttribute> reference in attrList)
{
PropertyInfo pi = reference.Key;
if (pi.PropertyType != typeof(string) &&
(conv == null || !conv.CanConvertFrom(pi.PropertyType)))
continue;
string value;
if (pi.PropertyType == typeof(string))
value = pi.GetValue(data, null) as string;
else
value = conv.ConvertToString(pi.GetValue(data, null));
yield return new KeyValuePair<CDSReferenceAttribute, string>(reference.Value, value);
}
}
示例10: CanConvertToAndFromString
private static bool CanConvertToAndFromString(TypeConverter converter)
{
return converter.CanConvertFrom(typeof(string)) &&
converter.CanConvertTo(typeof(string));
}
示例11: TryConvertTo
private static bool TryConvertTo( object value, Type targetType, CultureInfo culture, TypeConverter converter, out object result )
{
if( converter != null )
{
try
{
result = converter.ConvertTo( null, culture, value, targetType );
return true;
}
catch
{
// We'll try to convert the value another way.
}
if( ( value != null ) && ( converter.CanConvertFrom( value.GetType() ) ) )
{
try
{
var newValue = converter.ConvertFrom( null, culture, value );
result = converter.ConvertTo( null, culture, newValue, targetType );
return true;
}
catch
{
}
}
}
result = null;
return false;
}
示例12: CreateConverter
private void CreateConverter() {
// Some properties cannot have type converters.
// Such examples are properties that are ConfigurationElement ( derived classes )
// or properties which are user-defined and the user code handles serialization/desirialization so
// the property itself is never converted to/from string
if (_converter == null) {
// Enums are exception. We use our custom converter for all enums
if (_type.IsEnum) {
_converter = new GenericEnumConverter(_type);
}
else if (!_type.IsSubclassOf(typeof(ConfigurationElement))) {
_converter = TypeDescriptor.GetConverter(_type);
if ((_converter == null) ||
!_converter.CanConvertFrom(typeof(String)) ||
!_converter.CanConvertTo(typeof(String))) {
throw new ConfigurationErrorsException(SR.GetString(SR.No_converter, _name, _type.Name));
}
}
}
}
示例13: ConvertObjectToTypeInternal
private static bool ConvertObjectToTypeInternal(object o, Type type, JavaScriptSerializer serializer, bool throwOnError, out object convertedObject)
{
IDictionary<string, object> dictionary = o as IDictionary<string, object>;
if (dictionary != null)
{
return ConvertDictionaryToObject(dictionary, type, serializer, throwOnError, out convertedObject);
}
IList list = o as IList;
if (list != null)
{
IList list2;
if (ConvertListToObject(list, type, serializer, throwOnError, out list2))
{
convertedObject = list2;
return true;
}
convertedObject = null;
return false;
}
if ((type == null) || (o.GetType() == type))
{
convertedObject = o;
return true;
}
//TypeDescriptor.GetConverter(type) !!!
TypeConverter converter = new TypeConverter();
if (converter.CanConvertFrom(o.GetType()))
{
try
{
convertedObject = converter.ConvertFrom(null, CultureInfo.InvariantCulture, o);
return true;
}
catch
{
if (throwOnError)
{
throw;
}
convertedObject = null;
return false;
}
}
if (converter.CanConvertFrom(typeof(string)))
{
try
{
string str;
if (o is DateTime)
{
DateTime time = (DateTime)o;
str = time.ToUniversalTime().ToString("u", CultureInfo.InvariantCulture);
}
else
{
//ConvertToInvariantString(o); !!!
str = converter.ConvertToString(o);
}
//ConvertFromInvariantString(str); !!!
convertedObject = converter.ConvertToString(str);
return true;
}
catch
{
if (throwOnError)
{
throw;
}
convertedObject = null;
return false;
}
}
if (type.IsAssignableFrom(o.GetType()))
{
convertedObject = o;
return true;
}
if (throwOnError)
{
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, AtlasWeb.JSON_CannotConvertObjectToType, new object[] { o.GetType(), type }));
}
convertedObject = null;
return false;
}
示例14: APXmlProperty
/// <summary>
/// Creates a new instance of the ConfigurationProperty class.
/// </summary>
/// <param name="name">The name of the xml entity.</param>
/// <param name="type">The type of the xml entity.</param>
/// <param name="defaultValue">The default value of the xml entity.</param>
/// <param name="converter">The type of the converter to apply.</param>
/// <param name="validation">The validator to use.</param>
/// <param name="flags">One of the APXmlPropertyOptions enumeration values.</param>
/// <param name="description">The description of the xml entity.</param>
public APXmlProperty(string name, Type type, object defaultValue,
TypeConverter converter, APValidatorBase validation, APXmlPropertyOptions flags, string description)
{
_name = name;
_converter = converter != null ? converter : TypeDescriptor.GetConverter(type);
if (defaultValue != null)
{
if (defaultValue == NoDefaultValue)
{
switch (Type.GetTypeCode(type))
{
case TypeCode.Object:
defaultValue = null;
break;
case TypeCode.String:
defaultValue = String.Empty;
break;
default:
defaultValue = Activator.CreateInstance(type);
break;
}
}
else
{
if (!type.IsAssignableFrom(defaultValue.GetType()))
{
if (!_converter.CanConvertFrom(defaultValue.GetType()))
throw new APXmlException(APResource.GetString(APResource.APXml_DefaultValueTypeError, name, type, defaultValue.GetType()));
defaultValue = _converter.ConvertFrom(defaultValue);
}
}
}
_defaultValue = defaultValue;
_flags = flags;
_type = type;
_validation = validation != null ? validation : new DefaultAPValidator();
_description = description;
}
示例15: ParseFormattedValue
public virtual object ParseFormattedValue (object formattedValue, DataGridViewCellStyle cellStyle, TypeConverter formattedValueTypeConverter, TypeConverter valueTypeConverter)
{
if (cellStyle == null)
throw new ArgumentNullException ("cellStyle is null.");
if (FormattedValueType == null)
throw new FormatException ("The System.Windows.Forms.DataGridViewCell.FormattedValueType property value is null.");
if (formattedValue == null)
throw new ArgumentException ("formattedValue is null.");
if (ValueType == null)
throw new FormatException ("valuetype is null");
if (!FormattedValueType.IsAssignableFrom (formattedValue.GetType ()))
throw new ArgumentException ("formattedValue is not of formattedValueType.");
if (formattedValueTypeConverter == null)
formattedValueTypeConverter = FormattedValueTypeConverter;
if (valueTypeConverter == null)
valueTypeConverter = ValueTypeConverter;
if (valueTypeConverter != null && valueTypeConverter.CanConvertFrom (FormattedValueType))
return valueTypeConverter.ConvertFrom (formattedValue);
if (formattedValueTypeConverter != null && formattedValueTypeConverter.CanConvertTo (ValueType))
return formattedValueTypeConverter.ConvertTo (formattedValue, ValueType);
return Convert.ChangeType (formattedValue, ValueType);
}