C# 运行时类型化/泛型变量

C# 运行时类型化/泛型变量,c#,unity3d,design-patterns,dynamic,C#,Unity3d,Design Patterns,Dynamic,我正在寻找实现类似于下面的类的方法,包含一个带有两个参数的构造函数,第二个参数是一个通用的运行时类型 我正在Unity 3D中使用.Net3.5 public class Parameter { private mParameterName; private T parameterValue; // runtime parameter public Parameter( string parameterName, string parameterValue ){}

我正在寻找实现类似于下面的类的方法,包含一个带有两个参数的构造函数,第二个参数是一个通用的运行时类型

我正在Unity 3D中使用.Net3.5

public class Parameter
{
    private mParameterName;
    private T parameterValue; // runtime parameter

    public Parameter( string parameterName, string parameterValue ){}
    public Parameter( string parameterName, long parameterValue ){}
    public Parameter( string parameterName, double parameterValue ){}
}

任何正确方向上的帮助都会很棒。提前感谢。

通常,您必须按如下方式精确说明课程中的类型
T

public class Parameter<T>
{
    private string mParameterName;
    private T parameterValue; // runtime parameter

    public Parameter( string parameterName, T parameterValue ){}
}
公共类参数
{
私有字符串mParameterName;
私有T参数值;//运行时参数
公共参数(字符串参数名,T参数值){}
}

这很容易做到:

public class Parameter<T>
{
    private string mParameterName;
    private T parameterValue; // runtime parameter

    public Parameter( string parameterName, T parameterValue )
    {
        this.mParameterName = parameterName;
        //this. is required below because the method parameter and class member
        //have the same name, so this. refers to the class member and without
        //refers to the method parameter.
        this.parameterValue = parameterValue;
    }
}
公共类参数
{
私有字符串mParameterName;
私有T参数值;//运行时参数
公共参数(字符串参数名称,T参数值)
{
this.mParameterName=参数名称;
//由于方法参数和类成员
//具有相同的名称,因此this.指的是类成员,没有
//指方法参数。
this.parameterValue=parameterValue;
}
}

在这里,您可以在类名中定义泛型类型参数:
公共类参数
,然后可以在构造函数中使用它。每种类型都不需要新的构造函数。

谢谢您的回复。是否可以强制T仅为String、Int和float?仅在编译时?@Yasantha否,您可以将其限制为结构(值类型)或引用类型,但无法将其限制为特定类型的列表。您可以将其限制为接口或非密封类。