我有以下代码,它执行非常简单的操作:递归访问Node对象树,并计算名为Info的属性的总和。
更好的解决方案是:
我的问题和疑问是:为什么我不能在方法内部使用函数?我得到了错误:使用未赋值的本地变量“fSum”。
using System;
namespace ConsoleApplication11
{
static class Program
{
static void Main(string[] args)
{
//tree of nodes
var node = new Node {Info = 1, Left = new Node {Info = 1}};
//print out sum
Console.WriteLine(node.Sum());
Console.ReadLine();
}
//find sum of Info of each node
static int Sum(this Node node)
{
return node.Info + (node.Left == null ? 0 : Sum(node.Left)) + (node.Right == null ? 0 : Sum(node.Right));
}
}
public class Node
{
public int Info { get; set; }
public Node Left { get; set; }
public Node Right { get; set; }
}
}
更好的解决方案是:
using System;
namespace ConsoleApplication11
{
static class Program
{
static Func<Node, int> fSum = (node) => node.Info + (node.Left == null ? 0 : fSum(node.Left)) + (node.Right == null ? 0 : fSum(node.Right));
static void Main(string[] args)
{
//tree of nodes
var node = new Node {Info = 1, Left = new Node {Info = 1}};
//print out sum
Console.WriteLine(fSum(node));
Console.ReadLine();
}
}
public class Node
{
public int Info { get; set; }
public Node Left { get; set; }
public Node Right { get; set; }
}
}
我的问题和疑问是:为什么我不能在方法内部使用函数?我得到了错误:使用未赋值的本地变量“fSum”。
using System;
namespace ConsoleApplication11
{
static class Program
{
static void Main(string[] args)
{
//I am getting error: Use of unassigned local variable 'fSum'
Func<Node, int> fSum = (node) => node.Info + (node.Left == null ? 0 : fSum(node.Left)) + (node.Right == null ? 0 : fSum(node.Right));
//tree of nodes
var n = new Node {Info = 1, Left = new Node {Info = 1}};
//print out sum
Console.WriteLine(fSum(n));
Console.ReadLine();
}
}
public class Node
{
public int Info { get; set; }
public Node Left { get; set; }
public Node Right { get; set; }
}
}