2017-08-26 48 views
0

System.Reflection.TargetException:對象與目標類型不匹配。如何運行GetMethod.Invoke?我得到錯誤

public class Parameter : BaseEntity 
{ 
    ... 
    ... 

    public override void Map(ModelBuilder modelBuilder) 
    { 
     modelBuilder.Entity<Parameter>(opt => 
     { 
      opt.ToTable("Parameter"); 
      opt.HasKey(x => x.Id); 
      opt.Property(x => x.AutoId).UseSqlServerIdentityColumn(); 
      opt.HasAlternateKey(x => x.AutoId); 
     }); 
    } 
} 


public class DataContext<T> : DbContext where T : BaseEntity 
{ 
    ... 
    ... 

    protected override void OnModelCreating(ModelBuilder modelBuilder) 
    { 
     Type t = typeof(T); 
     t.GetMethod("Map").Invoke(this, new object[] { modelBuilder }); // this line ***** 
    } 
} 

T被稱爲Parameter類。和(/ /這行*****)方面給我錯誤。

System.Reflection.TargetException:Object與目標類型不匹配。

我該如何運行?

+0

那麼,你用'this'調用它,'this'不是'Parameter',而是'DataContext ',這就是爲什麼它不起作用。你有一個你想要使用的'Parameter'的實例嗎? –

+0

其實我試過't'而不是'this'。我得到了同樣的錯誤。我想寫T在那裏,它必須是通用的。我有x20類更像'Parameter',他們有'Map' void。我必須打電話給他們來運行這個項目。 –

+0

委託給你的代碼't'是'T'的'Type',而不是'T'的實例。 –

回答

1

如果創建一個Minimal, Complete, and Verifiable example,類似下面的(甚至參數類型無關),你的問題立刻變得很明顯:

class ArgumentType 
{ 

} 

class Foo 
{ 
    public void Bar(ArgumentType argument) 
    { 
    } 
} 

class Program 
{ 
    static void Main(string[] args) 
    { 
     Type t = typeof(Foo); 

     var argument = new ArgumentType(); 

     t.GetMethod("Bar").Invoke(this, new object[] { argument }); 
    } 
} 

你調用上this的方法,這是 a Foo(或您的案例中的T),所以你會得到這個例外。

修復代碼,您需要實例T並調用該方法:

var instance = new Foo(); // or new T() in your case 

t.GetMethod("Bar").Invoke(instance, new object[] { argument }); 

你還必須限制Tnew()爲工作,以表明過去了T這種類型的論據有一個無參數的構造函數,所以你可以在那裏實例化它。

+0

我懂了!我使用Activator創建了實例。非常感謝你的想法。 –

相關問題