如何使用2种通用类型创建流畅的方法?

时间:2016-07-07 09:22:08

标签: c#

我有以下类(为简单起见省略了属性):

public class Person {
  public Address Address { get; set; }
  public Hobby Hobby { get; set; }
}

public class Address {
  public Country Country { get; set; }
}

public class Country { }

public class Hobby { }

如果可能的话,我创建了一个IncludeMapper,如下所示:

IncludeMapper<Person> m = IncludeMapper
  .For<Person>()
  .Add(person => person.Address).And(address => address.Country)
  .Add(person => person.Hobby);

添加将采用基本类型,例如Person 将采用上一个Add或And中使用的类型。

public class IncludeMapper {
  public static IncludeMapper<T> For<T>() {
    return new IncludeMapper<T>();
  }
}

public class IncludeMapper<T> {

  public IncludeMapper<T> Add<K>(String expression, Expression<Func<T, K>> property) {
    return this;
  }

  public IncludeMapper<K> And<K>(String expression, Expression<Func<T, K>> property) {
    return this;
  }
}

这不起作用......我想我需要返回方法,我可能需要一个额外的类,因为For只适用于T?

有人可以帮我解决这个问题吗?

0 个答案:

没有答案