为什么委托类型的属性不起作用?

时间:2012-09-20 10:03:54

标签: c# .net properties delegates

有人可以解释为什么这段代码不起作用吗?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        public delegate void Something(string s);

        public class TestDelegate
        {
            public Something something
            {
                set
                {
                    Console.WriteLine("Registering delegate: {0}", something);
                    something = value;
                    Console.WriteLine("Delegate registered: {0}", something);
                }

                get
                {
                   Console.WriteLine("Get delegate");
                   return something;
                }
            }

            public void doSomething(string s)
            {
                something(s);
            }
        }

        static void Main(string[] args)
        {
            TestDelegate td = new TestDelegate();
            td.something = (string s) => Console.WriteLine(s);
            td.doSomething("test");
        }
    }
}

1 个答案:

答案 0 :(得分:6)

您的问题与代表无关。您的财产只是一个无休止的递归案例。该属性在访问器而不是支持字段中访问自身 像这样改变它应该有效:

private Something _something;
public Something something
{
    set
    {
        Console.WriteLine("Registering delegate: {0}", value);
        _something = value;
        Console.WriteLine("Delegate registered: {0}", something);
    }

    get
    {
       Console.WriteLine("Get delegate");
       return _something;
    }
}