我試圖用一個通用方法來生成一個過濾器。過濾器是一個抽象的類。SomeFilter類將擴展Filter。我想要一個像這樣的方法:
protected Filter GenerateFilter< T> () where T : 過濾器
{
if (T == SomeFilter)
{
return new SomeFilter()。
}
編輯: 我是C#的新手,從Java過來的。這些解決方案對我理解C#泛型有很大的幫助。謝謝你的幫助。我確實會繼續使用FilterFactory。我曾希望我能夠用泛型來完成它,但工廠仍然是更好的實作方式。
謝謝你!
uj5u.com熱心網友回復:
你可以將new()約束添加到T型別引數中,然后像這樣改變你的方法:
protected Filter GenerateFilter< T>() where T : 過濾器,new()
{
return new T()。
}
uj5u.com熱心網友回復:
使用反射來創建實體
protected Filter GenerateFilter< T>() where T : 過濾器
{
return Activator.CreateInstance<T>()。
}
uj5u.com熱心網友回復:
我認為你是在關注每個個案的檢查情況
public static T Generate< T>() whereT: 過濾器
{
var t = typeof(T)。
if (t == typeof(SomeFilter) >)
{
return new SomeFilter() as T。
}
if (t == typeof(OtherFilter))
{
return new OtherFilter() as T。
}
throw new NotSupportedException();
這可能是一個具有已知型別的類層次結構的一部分。
如果過濾器來自于一個插件,這意味著在編譯時并非所有的具體型別都是已知的,那么這將會落空。這將需要一個不同的架構,而op并沒有說明這一點。
另一個解決方案是每個具體型別都有一個默認的建構式,就是使用
new()
public static T Generate< T>() where T: 過濾器,new()
{
return new T()。
}
<解釋一下
第三種選擇是在過濾器類中使用一個遞延型別,只是一個如下:
static class Program
{
static void Program { title">Main(string[] args)?
{
SomeFilter filter = Filter<SomeFilter>.Generate()。
SomeFilter also = filter.Copy();
filter.Combine(also);
}
}
public abstract class Filter< TFilter> where TFilter: Filter<TFilter>, new( )
{
public static TFilter Generate()
{
return new TFilter()。
}
public TFilter Copy()=> this. MemberwiseClone() as TFilter;
public abstract void Combine(TFilter other)。
}
public class SomeFilter : Filter<SomeFilter>
{
public float Alpha { get; set; }
public override void Combine(SomeFilter other)
{
this.Alpha *= other.Alpha。
}
}
public class OtherFilter : Filter<OtherFilter>
{
public int Strength { get; set; }
public override void Combine(OtherFilter other)
{
this.Strength = Math.Max(Strength, other.Strength)。
}
基類知道TFilter中派生類的型別的好處是,它可以在方法中使用,如上面的Combine()和Copy(),并且在實作時它將決議為正確的型別。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/318600.html
標籤:
