本文整理汇总了C#中System.Dynamic.DynamicObject.TryConvert方法的典型用法代码示例。如果您正苦于以下问题:C# DynamicObject.TryConvert方法的具体用法?C# DynamicObject.TryConvert怎么用?C# DynamicObject.TryConvert使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Dynamic.DynamicObject
的用法示例。
在下文中一共展示了DynamicObject.TryConvert方法的1个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: TryGetMember
// The class derived from DynamicObject.
public class DynamicNumber : DynamicObject
{
// The inner dictionary.
Dictionary<string, object> dictionary
= new Dictionary<string, object>();
// Getting a property.
public override bool TryGetMember(
GetMemberBinder binder, out object result)
{
return dictionary.TryGetValue(binder.Name, out result);
}
// Setting a property.
public override bool TrySetMember(
SetMemberBinder binder, object value)
{
dictionary[binder.Name] = value;
return true;
}
// Converting an object to a specified type.
public override bool TryConvert(
ConvertBinder binder, out object result)
{
// Converting to string.
if (binder.Type == typeof(String))
{
result = dictionary["Textual"];
return true;
}
// Converting to integer.
if (binder.Type == typeof(int))
{
result = dictionary["Numeric"];
return true;
}
// In case of any other type, the binder
// attempts to perform the conversion itself.
// In most cases, a run-time exception is thrown.
return base.TryConvert(binder, out result);
}
}
class Program
{
static void Test(string[] args)
{
// Creating the first dynamic number.
dynamic number = new DynamicNumber();
// Creating properties and setting their values
// for the dynamic number.
// The TrySetMember method is called.
number.Textual = "One";
number.Numeric = 1;
// Implicit conversion to integer.
int testImplicit = number;
// Explicit conversion to string.
string testExplicit = (String)number;
Console.WriteLine(testImplicit);
Console.WriteLine(testExplicit);
// The following statement produces a run-time exception
// because the conversion to double is not implemented.
// double test = number;
}
}
输出:
1 One