我有一個容器類,它具有受限於某些基類的泛型參數。提供給泛型的類型是基類約束的子類。子類使用方法隱藏(新)來改變方法從基類的行爲(不,我不能讓它變成虛擬的,因爲它不是我的代碼)。我的問題是'new'方法沒有被調用,編譯器似乎認爲提供的類型是基類,而不是sub,就好像我已經把它轉換爲基類。如何在通用約束類中使用方法隱藏(新)
很明顯,我誤解了一些根本性的東西。我認爲通用where T: xxx
是一個約束,而不是一個upcast類型。
此示例代碼基本上演示了我在說什麼。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GenericPartialTest
{
class ContextBase
{
public string GetValue()
{
return "I am Context Base: " + this.GetType().Name;
}
public string GetOtherValue()
{
return "I am Context Base: " + this.GetType().Name;
}
}
partial class ContextSub : ContextBase
{
public new string GetValue()
{
return "I am Context Sub: " + this.GetType().Name;
}
}
partial class ContextSub
{
public new string GetOtherValue()
{
return "I am Context Sub: " + this.GetType().Name;
}
}
class Container<T> where T: ContextBase, new()
{
private T _context = new T();
public string GetValue()
{
return this._context.GetValue();
}
public string GetOtherValue()
{
return this._context.GetOtherValue();
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Simple");
ContextBase myBase = new ContextBase();
ContextSub mySub = new ContextSub();
Console.WriteLine(myBase.GetValue());
Console.WriteLine(myBase.GetOtherValue());
Console.WriteLine(mySub.GetValue());
Console.WriteLine(mySub.GetOtherValue());
Console.WriteLine("Generic Container");
Container<ContextBase> myContainerBase = new Container<ContextBase>();
Container<ContextSub> myContainerSub = new Container<ContextSub>();
Console.WriteLine(myContainerBase.GetValue());
Console.WriteLine(myContainerBase.GetOtherValue());
Console.WriteLine(myContainerSub.GetValue());
Console.WriteLine(myContainerSub.GetOtherValue());
Console.ReadKey();
}
}
}
編輯:
我想我的困惑來自於一個能做到這一點
class SomeClass<T> where T: AnotherType, new()
{
T foo = new T();
}
而且我預計T
是T
即使我明白,編譯器會認爲T
爲有AnotherType
的界面。我認爲即使T
的界面是在編譯時設置的,運行時也會發生T
的打字。該T foo
聲明似乎誤導這裏,因爲它是真正做
AnotherType foo = new T();
一旦我明白,這是不是真的宣佈foo
爲T
型,這是可以理解爲什麼new
方法隱藏是行不通的。我不得不說這些。
可能的重複http://stackoverflow.com/questions/774726/generics-accessing-new-members-not-hidden-members – 2010-04-15 22:59:38