我在想,如果有可能运行下面的代码,但没有拆箱行: -从字典<字符串,对象>不拆箱获取价值?
t.Value = (T)x;
或者,也许如果有另一种方式做这种手术?
下面是完整的代码: -
public class ValueWrapper<T>
{
public T Value { get; set; }
public bool HasValue { get; set; }
public ValueWrapper()
{
HasValue = false;
}
}
class Program
{
static void Main(string[] args)
{
Dictionary<string, object> myDictionary = new Dictionary<string, object>();
myDictionary.Add("key1", 6);
myDictionary.Add("key2", "a string");
var x2 = GetValue<int>(myDictionary, "key1");
if (x2.HasValue)
Console.WriteLine("'{0}' = {1}", "key1", x2.Value);
else
Console.WriteLine("No value found");
Console.ReadLine();
}
static ValueWrapper<T> GetValue<T>(IDictionary<string, object> dictionary, string key)
{
ValueWrapper<T> t = new ValueWrapper<T>();
object x = null;
if (dictionary.TryGetValue(key, out x))
{
if (x.GetType() == typeof(T))
{
t.Value = (T)x;
t.HasValue = true;
}
}
return t;
}
}
在此先感谢!
Richard。
不,如果你的'object'被装箱值类型,然后它会需要拆箱。你有什么理由要避免拆箱? – LukeH 2010-10-20 22:30:04
主要是因为我的项目中的代码与其他东西一起使用时的性能,拆箱会将执行时间从〜200ms增加到〜1700ms。这仍然是可以接受的,如果有其他选择,我只是想知道为了我自己的利益。 – 2010-10-20 22:46:54
这种剧烈的性能下降是由于拆箱造成的。使用分析器来确定真正的瓶颈是什么。 – Timwi 2010-10-20 23:35:57