c#用索引器实现使用属性名称获取属性对象
时间: 2024-03-02 16:49:12 浏览: 23
在C#中,可以使用索引器来实现使用属性名称获取属性对象。下面是一个示例:
```csharp
using System;
using System.Collections.Generic;
class MyClass
{
private Dictionary<string, object> properties = new Dictionary<string, object>();
public object this[string propertyName]
{
get
{
if (properties.ContainsKey(propertyName))
{
return properties[propertyName];
}
else
{
throw new ArgumentException("Invalid property name");
}
}
set
{
properties[propertyName] = value;
}
}
}
class Program
{
static void Main(string[] args)
{
MyClass myObject = new MyClass();
myObject["Name"] = "John";
myObject["Age"] = 30;
Console.WriteLine("Name: {0}", myObject["Name"]);
Console.WriteLine("Age: {0}", myObject["Age"]);
}
}
```
在上面的示例中,`MyClass`类包含一个名为`properties`的字典,它将属性名作为键,属性值作为值。然后,`MyClass`类实现了一个名为`this`的索引器,它接受一个字符串参数,该参数作为属性名称。在索引器的`get`方法中,它检查`properties`字典中是否存在该属性,并返回该属性的值。在索引器的`set`方法中,它将该属性的值设置为提供的值。在`Main`方法中,我们使用索引器来设置和获取`Name`和`Age`属性的值。
需要注意的是,这种实现方式存在一些潜在的问题。例如,如果属性名称拼写错误,则会引发`ArgumentException`异常。此外,索引器可能会返回任何类型的属性值,因此需要进行类型检查。