这是Action <t> </t>的正确用法

时间:2013-11-19 20:22:49

标签: c# delegates

据我了解Func和Action; Action不返回值,而Func则返回值。在下面的示例中,我有一个子类创建一个“SomeContent”实例,并将引用传递回父类。我的问题是:

  1. this.ContentDelagate(content)是通过引用还是按值传递的?

  2. 在下面的例子中,我是否应该使用Func,因为我想要一个实例化的SomeContent对象的引用?如果是这样,你能提供一个例子吗?


  3. namespace DelegateTut
    {
        class Program
        {       
            static void Main(string[] args)
            {
    
                TestClass myTest = new TestClass();
    
                myTest.ContentDelagate += ContentDelegateHandler;       
                myTest.RunDel();          
    
    
                Console.Write("Press Enter to exit...\n");
                Console.ReadLine();
    
            }
            public static void ContentDelegateHandler(SomeContent content) {
    
                Console.WriteLine(content.ValueOne);
                Console.WriteLine(content.ValueTwo);
    
            }     
    
        }
    }
    
    public class TestClass {
    
        public TestClass() { }   
    
        public Action<SomeContent> ContentDelagate { get; set; }   
    
        public void RunDel() {
    
            SendContentToMainThread();
    
        }   
    
        public void SendContentToMainThread() {
    
            SomeContent content = new SomeContent { 
    
                ValueOne = "Hello",
                ValueTwo = "World"
    
            };
    
            this.ContentDelagate(content);
        }   
    
    }
    
    public class SomeContent {
    
        public String ValueOne { get; set; }
        public String ValueTwo { get; set; }
        public SomeContent() { }
    
    }
    

1 个答案:

答案 0 :(得分:2)

  

this.ContentDelagate(content)是通过引用还是按值传递?

这个问题有点令人困惑。我们也在处理吸气剂和代表。我认为更清楚地表明:

    public void SendContentToMainThread()
    {

        SomeContent content = new SomeContent
        {

            ValueOne = "Hello",
            ValueTwo = "World"

        };

        Action<SomeContent>  myDel = ContentDelagate;//Property Get 
        myDel(content);//invoke delegate

        Console.WriteLine(content.ValueOne);//refer to this below
    }

处理程序作为多播委托的一部分进行调用。处理程序正在传递一个类,它是一个引用类型。在C#中,引用和值类型按值传递。复制的基础值可以是值(值类型)或内存中的位置(引用类型)。

因为这是一个引用类型,所以它具有引用类型行为:

        public static void ContentDelegateHandler(SomeContent content)
        {
            Console.WriteLine(content.ValueOne);
            Console.WriteLine(content.ValueTwo);

            content.ValueOne = "updated";
        }

现在,Console.WriteLine(content.ValueOne);上面的修改后的代码会打印出“已更新”字样。

  

在下面的例子中,我应该使用Func,因为我想要一个引用   一个实例化的SomeContent对象?如果是这样,你可以提供   示例

在这种情况下没有返回任何内容所以你不应该使用Func。 Func对您希望引用类型行为没有任何影响。

相关问题