本文整理匯總了C#中System.Dynamic.DynamicObject.TrySetIndex方法的典型用法代碼示例。如果您正苦於以下問題:C# DynamicObject.TrySetIndex方法的具體用法?C# DynamicObject.TrySetIndex怎麽用?C# DynamicObject.TrySetIndex使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類System.Dynamic.DynamicObject
的用法示例。
在下文中一共展示了DynamicObject.TrySetIndex方法的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