我寫了一個泛型類,並希望從靜態方法中創建它的實例。問題是我無法創建對象的通用實例。我知道這聽起來很混亂,最好是展示代碼。泛型類型的返回實例
public class Parameter<T> : IParameter<T>
{
public string Name { get; set; }
public T Value { get; set; }
public bool IsValid()
{
if (String.IsNullOrEmpty(Name))
return false;
return (typeof(T) == typeof(String)) ||
typeof(T) == typeof(bool) ||
typeof(T) == typeof(int) ||
typeof(T) == typeof(double);
}
public XElement ToXml()
{
if (!IsValid())
throw new InvalidParameterException();
var xElement = new XElement("Parameter", Value,
new XAttribute("Type", typeof (T)),
new XAttribute("Name", Name));
return xElement;
}
public static Parameter<T> FromXml(XElement xElement)
{
var sType = xElement.Attributes()
.Where(attribute => attribute.Name == "Type")
.Single().Name.ToString();
var name = xElement.Attributes()
.Where(attribute => attribute.Name == "Name")
.Single().Name.ToString();
var sValue = xElement.Value;//need to use this
var typeVar = Type.GetType(sType);// and this to create proper instance of Parameter<T>
//I need somehow set T equal to typeVar here and Set
return new Parameter<T>() {Name = name};//this is wrong.
//I need return either Parameter<int> or Paramter<double> or Parameter<string> or Parameter<bool>
//basing on typeVar
}
}
我不確定這是否有可能...但看起來像它是微不足道的對象設計要求。有任何想法嗎? 謝謝!
UPD:我正在使用.NET 4.0。它有什麼區別? :)
UPD2:現在看問題,我看到這是一個愚蠢的問題。並且返回這樣的「通用」對象是不可能的。
這是完全不可能從方法內部設置'T'。想想:你怎麼可能稱這種方法? – SLaks 2011-04-12 16:30:29
var parameter = Parameter.FromXml(element); ? :) – 2011-04-12 16:38:22
ofcourse你可以潛入動態領域,但我不會潛入那一個快速;) – Polity 2011-04-12 16:41:06