c#中GetMethod?.Invoke
时间: 2023-06-30 07:08:29 浏览: 58
这段代码使用了C# 6.0的null条件运算符。GetMethod?.Invoke的意思是:如果GetMethod方法返回null,则不会执行Invoke方法,避免了空引用异常。它等效于以下代码:
```
var method = GetMethod();
if (method != null)
{
method.Invoke();
}
```
相关问题
C#中type.GetProperty.GetMethod.Invoke
在C#中,type.GetProperty.GetMethod.Invoke方法用于调用指定对象的属性或方法。其中,GetProperty和GetMethod方法用于获取属性或方法的信息,而Invoke方法则用于调用它们。
例如,以下代码可以获取名为"Age"的属性,并调用它的Get方法来获取对象person的年龄:
```
Type type = typeof(Person);
PropertyInfo propertyInfo = type.GetProperty("Age");
MethodInfo getMethod = propertyInfo.GetGetMethod();
object person = new Person();
object age = getMethod.Invoke(person, null);
```
这里的Person是一个自定义类,Age是其中的一个属性。Invoke方法接受两个参数:第一个参数是要调用的对象,第二个参数是方法的参数(如果有)。在上面的例子中,因为Age属性的Get方法不接受任何参数,所以第二个参数为null。
C#中如何实现反射
C#中,可以使用System.Reflection命名空间下的类来实现反射。以下是一个简单的示例:
```csharp
using System;
using System.Reflection;
class MyClass {
private int myField;
public MyClass() {
myField = 42;
}
public void MyMethod() {
Console.WriteLine("This is my method.");
}
}
class Program {
static void Main(string[] args) {
Type t = typeof(MyClass);
Console.WriteLine("Type name: " + t.Name);
Console.WriteLine("Full name: " + t.FullName);
FieldInfo[] fields = t.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
foreach (FieldInfo field in fields) {
Console.WriteLine("Field name: " + field.Name);
Console.WriteLine("Field type: " + field.FieldType);
Console.WriteLine("Field value: " + field.GetValue(new MyClass()));
}
MethodInfo method = t.GetMethod("MyMethod");
method.Invoke(new MyClass(), null);
}
}
```
上述示例中,我们首先使用typeof关键字获取类型MyClass的Type对象。然后,我们使用Type对象获取该类型的信息,如名称、完整名称、字段、方法等。我们还使用反射获取私有字段的值,并调用方法。这些都是通过System.Reflection命名空间下的类来实现的。