如何在列表中存储通用类而不指定类型? - c#

我有以下课程:

class Parameter<T>
{
    public string Index { get; set; }
    public T Value { get; set; }
}

我想要一个这样的列表:

class ParameterModel
{
    public List<Parameter<>> Parameters {get;}
}

然后,我将得到如下代码:

...
Parameter<> parameter = parameterModel.Parameters.Where(p => p.Index == "AAA");
if (parameter is Parameter<bool>)
{
    ...
}
else if (parameter is Parameter<int>)
{
    ...
}
...

这是可行的还是应该使用继承而不是泛型?

提前致谢。

参考方案

不会

class ParameterModel<T>
{
    public List<Parameter<T>> Parameters { get; }
}

做这份工作?

还是您不想使用不同类型的参数?那你可以做

public interface IParameter
{
    string Index { get; set; }
    Type ParameterType { get; }
}

public class Parameter<T> : IParameter
{
    public string Index { get; set; }
    public T Value { get; set; }
    public Type ParameterType
    {
        get
        {
            return typeof(T);
        }
    }
}

class ParameterModel
{
    public List<IParameter> Parameters { get; }
}

所以你可以做

var aaaParameter = parameterModel.Parameters.Single(p => p.Index == "AAA");
if (aaaParameter.ParameterType == typeof(bool))
{
    ...
}
else if (aaaParameter.ParameterType == typeof(string))
{
    ...
}

但是,考虑到您描述的问题的范围,最好使用简单的字典。

var parameterModel = new Dictionary<string, object>();

允许

var aaaParameter = parameterModel["AAA"];
if (aaaParameter is bool)
{
    ...
}
else if (aaaParameter is string)
{
    ...
}

C#等效于Java List <?扩展类> - c#

我有泛型类的基本结构public class Parent<T> where T : Parent<T> { Action<T> Notify; } public class Child : Parent<Child> { } 我想要一个列表,以便可以将Child对象放在此处List<Parent>…

将对象转换为List <object> - c#

我看过类似的问题,但没有什么合适的。我有一个碰巧包含列表的对象。我想把它变成我可以列举的东西。例如:object listObject; // contains a List<Something> List<object> list; list = listObject as List<object>; // list c…

List <Dog>是List <Animal>的子类吗?为什么Java泛型不是隐式多态的? - java

我对Java泛型如何处理继承/多态感到困惑。假设以下层次结构-动物(父母)狗-猫(儿童)因此,假设我有一个方法doSomething(List<Animal> animals)。根据继承和多态性的所有规则,我假设List<Dog>是List<Animal>,而List<Cat>是List<Animal&g…

将谓词<T>转换为Func <T,bool> - c#

我有一个包含成员Predicate的类,希望在Linq表达式中使用该类:using System.Linq; class MyClass { public bool DoAllHaveSomeProperty() { return m_instrumentList.All(m_filterExpression); } private IEnumerable&…

当我所有的都是T时,如何返回Interface <T>的实例? - java

我有一个界面:public interface ILoginResult<T> { public T get(); } 我有一个LoginPage对象:public class LoginPage<T> { ... public ILoginResult<T> login(...) { ... } } 我也有一些登录页面对…