简体   繁体   English

List <T>项目的T的通用

[英]Generic of T for List<T> items

Apologies if this question has been asked before, I couldn't find anything similar. 如果以前问过这个问题,我道歉,我找不到类似的东西。

I have an enumerable choice that comes into my class: 我有一个可以选择进入我班级的选择:

public enum OrdinalValue
{
   None = 0,
   Qualification = 1,
   Career = 2,
   Faculty = 3
}

Based on this enumerable do I have 3 property calls that brings back data from an entity collection for each of these: 基于这个可枚举的,我有3个属性调用,它们从实体集合中为每个调用带来数据:

public List<Qualification> ByQualification { get; set; }
public List<Career> ByCareer { get; set; }
public List<Faculty> ByFaculty { get; set; }

I want to create a generic method that returns the correct property, based on the enum passed back from the calling method, something like: 我想创建一个泛型方法,根据从调用方法传回的枚举返回正确的属性,如:

public List<T> GetEntities<T>(OrdinalValue ord)
{
    List<T> value = default(List<T>);

    // based on enum, cast the correct List<T> and return value
    // something like:
    if (ord == OrdinalValue.Career)
        return (List<T>)Convert.ChangeType(this.ByCareer, typeof(T));

    return value;
}

Is it possible? 可能吗?

It sounds like you want something like: 这听起来像你想要的东西:

public List<T> GetEntities<T>(OrdinalValue ord)
{
    object ret;

    switch(ord)
    {
        case OrdinalValue.Career:
            ret = ByCareer;
            break;
        case OrdinalValue.Faculty:
            ret = ByFaculty;
            break;
        case OrdinalValue.Qualification:
            ret = ByQualification;
            break;
        default:
            throw new ArgumentOutOfRangeException("ord");
    }
    return (List<T>) ret;
}

However, this doesn't feel like a good design to me. 然而,这对我来说并不是一个好的设计。 It's hard to suggest anything better without knowing more about the bigger picture, but it doesn't really feel like a truly generic method. 如果不了解更多关于更大图片的内容,很难提出更好的建议,但它并不像真正的通用方法。

I think @Jon is on the right track, there's no point in overcomplicating things here. 我认为@Jon是在正确的轨道上,在这里过分复杂的事情是没有意义的。 When maintaining the method gets too complicated you should think about doing it generically all the way. 当维护方法变得太复杂时,你应该考虑一直这样做。

However, I think his method can be simplified. 但是,我认为他的方法可以简化。 You don't need to pass the OrdinalValue parameter. 您不需要传递OrdinalValue参数。 Instead of checking it, you can check typeof(T) . 您可以检查typeof(T) ,而不是检查它。 The compiler will need to know T at compile time anyway. 编译器无论如何都需要在编译时知道T.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM