0

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

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");
        }
    }
}
4

1 回答 1

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;
    }
}
于 2012-09-20T10:08:10.337 回答