none
请问,为什么在这里,编译器找不到泛型方法? RRS feed

  • 问题

  • public interface IAccount {
            decimal Balance { get; }
            string Name { get; }
        }
    
    //Account class.
        public class Account : IAccount {
            public string Name { get; private set; }
            public decimal Balance { get; private set; }
    
            public Account(string name, Decimal balance) {
                this.Name = name;
                this.Balance = balance;
            }
        }
    
    //Define a algorithm method in a single class.
        public static class Algorithm {
            public static T2 Accumulate<T1, T2>(IEnumerable<T1> source, Func<T1, T2, T2> action) {
                T2 sum = default(T2);
                foreach(T1 item in source) {
                    sum = action(item, sum);
                }
                return sum;
            }
    
        }
    //Calling the algorithm method in the Main() method.
    static void Main() {
                var accounts = new List<Account>()
                {
                    new Account("Christian", 10),
                    new Account("Stephanie", 20),
                    new Account("Angela", 30)
                };
    
                decimal amount = Algorithm.Accumulate(accounts, (item, sub) => sub -= item.Balance);
            }
    }
    
    //我的那个"Accumulate()"方法只有一个,也就是说,这个泛型的方法,为什么在调用的时候我"不显示写出类型",编译不通过...
    也就是说,要这样去调用:decimal amount = Algorithm.Accumulate<Account,decimal>(accounts, (item, sub) => sub -= item.Balance);
    
    定义的时候,怎么在调用的时候也要指明?


    2013年6月12日 3:54

答案

  • 你这里只有一个参数,当然可以,系统会默认判断。但是如果你定义了多余一个的参数泛型,你不显示指定的话系统无法智能判断那个类型参数具体对应哪个类型,譬如:

    Swap<K,V>到底是:

    Swap(K k, V v)

    还是

    Swap(V v,K k)

    ???

    一旦你定义了类型,那么具体的先后顺序也就确定了。


    If you think one reply solves your problem, please mark it as An Answer, if you think someone's reply helps you, please mark it as a Proposed Answer

    Help by clicking:
    Click here to donate your rice to the poor
    Click to Donate
    Click to feed Dogs & Cats


    Found any spamming-senders? Please report at: Spam Report

    2013年6月12日 6:29
    版主

全部回复