本文整理汇总了C#中System.Dynamic.DynamicObject.TryGetIndex方法的典型用法代码示例。如果您正苦于以下问题:C# DynamicObject.TryGetIndex方法的具体用法?C# DynamicObject.TryGetIndex怎么用?C# DynamicObject.TryGetIndex使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Dynamic.DynamicObject
的用法示例。
在下文中一共展示了DynamicObject.TryGetIndex方法的1个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: TryGetMember
// The class derived from DynamicObject.
public class SampleDynamicObject : DynamicObject
{
// The inner dictionary to store field names and values.
Dictionary<string, object> dictionary
= new Dictionary<string, object>();
// Get the property value.
public override bool TryGetMember(
GetMemberBinder binder, out object result)
{
return dictionary.TryGetValue(binder.Name, out result);
}
// Set the property value.
public override bool TrySetMember(
SetMemberBinder binder, object value)
{
dictionary[binder.Name] = value;
return true;
}
// Set the property value by index.
public override bool TrySetIndex(
SetIndexBinder binder, object[] indexes, object value)
{
int index = (int)indexes[0];
// If a corresponding property already exists, set the value.
if (dictionary.ContainsKey("Property" + index))
dictionary["Property" + index] = value;
else
// If a corresponding property does not exist, create it.
dictionary.Add("Property" + index, value);
return true;
}
// Get the property value by index.
public override bool TryGetIndex(
GetIndexBinder binder, object[] indexes, out object result)
{
int index = (int)indexes[0];
return dictionary.TryGetValue("Property" + index, out result);
}
}
class Program
{
static void Test(string[] args)
{
// Creating a dynamic object.
dynamic sampleObject = new SampleDynamicObject();
// Creating Property0.
// The TrySetMember method is called.
sampleObject.Property0 = "Zero";
// Getting the value by index.
// The TryGetIndex method is called.
Console.WriteLine(sampleObject[0]);
// Setting the property value by index.
// The TrySetIndex method is called.
// (This method also creates Property1.)
sampleObject[1] = 1;
// Getting the Property1 value.
// The TryGetMember method is called.
Console.WriteLine(sampleObject.Property1);
// The following statement produces a run-time exception
// because there is no corresponding property.
//Console.WriteLine(sampleObject[2]);
}
}
输出:
Zero 1