当属性是委托类型时,如何使用C#中的反射设置属性值? [英] How to set the property value using reflection in C# when the property is a delegate type?

查看:455
本文介绍了当属性是委托类型时,如何使用C#中的反射设置属性值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个dll中有一个属性,我在C#中使用反射功能。我想设置属性,属性类型是委托类型。



请让我知道使用Reflection设置属性所涉及的步骤。



我知道需要使用SetValue方法来执行此操作,但不知道如何设置委托类型的属性。



SetValue(objectName,1,null)是使用反射设置整数属性,但不知道如何设置委托类型的属性。



如何声明委托属性类型的变量并使用反射对其进行初始化?



请提供示例解决方案。

$
谢谢,

I have a property in a dll that i am using using Reflection feature in C#. I would like to set the property and the property type is a delegate type.

Please let me know the steps involved in setting the property using the Reflection.

I know that SetValue method need to be used to do this, but don't know how to set the property of the delegate type.

SetValue(objectName, 1, null) is to set an integer property using reflection, but don't know how to set the property of the delegate type.

How to declare a variable of the delegate property type and initialize it using reflection?

Please provide solution with an example.

Thanks,

Raghu Devisetti

Raghu Devisetti







推荐答案

这是一个例子。让我们假设这个属性是这样的:

Here is an example. Let's imagine that the property is like this:

public  Action< string> MyProperty {get; set;}

public Action<string> MyProperty { get; set; }

其中我使用Action< string>作为委托类型的示例。

where I used Action<string> as an example of a delegate type.

要设置该值,您需要一个此委托类型的实例。例如:

To set the value, you need an instance of this delegate type. For example:

操作< string> myDelegate =(s)=> Console.WriteLine(s );

Action<string> myDelegate = (s)=>Console.WriteLine(s);

这里我使用Lambda Expression来设置委托的值,但您也可以使用匿名委托或将委托指向正确类型的子程序。

Here I used a Lambda Expression to set the value of the delegate, but you could also have used an anonymous delegate or pointed the delegate to a subroutine of the correct type.

现在您可以将此值设置为您的属性:

Now you can set this value to your property:

SetValue(objectName,myDelegate,null)

SetValue(objectName, myDelegate, null)


这篇关于当属性是委托类型时,如何使用C#中的反射设置属性值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆