【问题标题】:passing a list of Types generically for use in a generic method [duplicate]通用传递类型列表以用于通用方法[重复]
【发布时间】:2015-10-05 10:48:39
【问题描述】:

给定类型列表:

public class TypeLists
{
    public static List<Type> types 
    {
        get
        {
            return new List<Type>() { typeof(ValueBool), typeof(ValueInt), typeof(ValueDouble), typeof(ValueString) };
        }
    }
}

我想传递此列表或其他列表,以便在一种方法中通用地使用它们,该方法将以下列方式转换随附的对象参数:

public static SettingValueUnit UsingAType<T>(object value)
{
    var a = (T)value;
}

我尝试实现它的使用:

foreach (Type t in TypeLists.types)
{
    SettingValueUnit ValueUnit = UsingAType<t>(D.SettingValue.value);
}

但我收到以下错误

错误 1 ​​'t' 由于其保护级别而无法访问

我受限于 .Net 3.5 紧凑型框架。 我将不胜感激。

【问题讨论】:

  • 我现在意识到这个错误的性质很奇怪,因为我正在使用紧凑框架的沙盒版本。

标签: c# generics .net-3.5 compact-framework


【解决方案1】:

我对您遇到的错误方法的性质感到惊讶,但对您一开始就遇到错误这一事实感到惊讶。

您不能将泛型参数指定为表达式 - 目的是使其成为类型的编译时规范。如果你真的想这样做,你需要使用反射:

// The ... is because we don't know the name of the type containing the method
Method method = typeof(...).GetMethod("UsingAType").MakeGenericMethod(t);
method.Invoke(...);

【讨论】:

    猜你喜欢
    • 2020-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-05
    • 2013-10-31
    • 1970-01-01
    相关资源
    最近更新 更多