我只找到了這個問題的較舊答案,這就是為什么我再次嘗試,希望有一個解決方案。
我有一個通用類,它采用實作特定介面的類的物件。我可以輕松地撰寫一個類,在此介面型別的變數上實作該介面。
我不能做的是,創建一個泛型類,它接受一個類的實體,并將它寫在同一個泛型類的變數上,該類只需要它的類來實作介面。
public interface IBar {}
public class Foo : IBar {}
public class MyClass<T> where T : IBar
{
public T Value { get; set; }
}
// works
IBar fooAsBar = new Foo();
// visual studio / compiler says no...
MyClass<IBar> classWithFooAsBar = new MyClass<Foo>();
有什么方法可以讓我以某種方式將 MyClass 轉換為 MyClass?如果我需要它,我只需要訪問 Value 屬性,其他一切對我來說都無關緊要。
uj5u.com熱心網友回復:
正如評論所提到的,由于某些原因,這基本上是不可能的。我為實作我的目標所做的是創建一個包裝類:
public interface IBar {}
public class Foo : IBar {}
public class MyClass<T> where T : IBar
{
public T Value { get; }
}
public class MyWrapper
{
public IBar Value { get; }
public MyWrapper(IBar myBar)
{
this.Value = myBar;
}
}
// works
IBar fooAsBar = new Foo();
// visual studio / compiler says yes...
MyWrapper classWithFooAsBar = new MyWrapper(new Foo());
IBar myBar = classWithFooAsBar.Value;
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/376254.html
上一篇:Java引數化類
