我有這個帶有約束的通用方法ILogicPointContext。此方法呼叫具有相同約束的其他泛型方法,但代碼拋出例外,因為我需要型別是正確的,而不是介面型別。
public void DoSomething<TContext>(TContext ctx)
where TContext : ILogicPointContext
{
var typeOfCtx = ctx.GetType(); // CcpContex
var typeOfT = typeof(TContext); // ILogicPointContext
...
我有另一個類似的方法,其中方法的泛型型別是我傳遞給他的物件的泛型型別,這很好用
private void InsertStepDefinition<TContext>(PipelineStepDefinition<TContext> stepInfo)
where TContext : ILogicPointContext
在這種情況下,TContext 不是介面而是正確的型別。
我錯過了什么?
uj5u.com熱心網友回復:
泛型在使用變數型別呼叫時會自動決議(而不是使用 <> 呼叫方法)。
例子:
void Main()
{
Foo var1 = new Foo();
ILogicPointContext var2 = var1;
DoSomething(var1); //outputs Foo: generic resolution is automatically done on variable type
DoSomething(var2); //outputs ILogicPointContext, for the same reason
}
interface ILogicPointContext{}
class Foo:ILogicPointContext{}
void DoSomething<TContext>(TContext ctx)
where TContext : ILogicPointContext
{
Console.WriteLine(typeof(TContext).Name);
}
第二個輸出是 TContext 的實際型別,泛型是“創建”并在方法中使用的型別。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/460204.html
