[英]C# InvokeMember - MissingMethodException: 'Method not found'
在 .NET Core 6 RestAPI 應用程序中,我正在跟蹤全球證券交易所並有一個名為“ex”的以下交易所 class 的實例。
public class Exchange
{
public string CountryCode { get; set; }
public string Currency { get; set; }
public string DataSourceCode { get; set; }
public int DaysHoursId { get; set; }
public string ExchangeCode { get; set; }
public string ExchangeName { get; set; }
public int Id { get; set; }
public bool IsActive { get; set; }
public DateTimeOffset LastUpdatedDate { get; set; }
public string LastUpdatedStatus { get; set; }
public DateTimeOffset NextUpdateDateTime { get; set; }
public string Region { get; set; }
public string Timezone { get; set; }
public string Type { get; set; }
public string Url { get; set; }
public string Website { get; set; }
}
所有字段都填充有非空數據。 在這種情況下,我的 Postman 調用的主體是:{ "CountryCode": "USA", "Currency": "USD", "DataSourceCode": "IA2", "DaysHoursId": 2, "ExchangeCode": "AMEX" , "交易所名稱": "AMEX",
"IsActive": true, "LastUpdatedDate": "2022-04-24T15:42:28.2533333+00:00", "LastUpdatedStatus": "OK", "NextUpdateDateTime": "2022-04-24T15:42:28.2533333+00 :00", "Region": "NORTH AMERICA", "Timezone": "EST", "Type": "STOCK", "Url": "https://www.nyse.com/markets/nyse-american" , "網站": "www.AMEX.com" }
使用反射,我從這個 object 創建了一個數據表,其中包含除“Id”之外的所有列,它是表中將加載數據的身份主鍵,如下所示:
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(ex);
DataTable dt = new DataTable();
foreach (PropertyDescriptor p in props)
{
if (p.Name != "Id") // insert into an identity column not allowed.
{
dt.Columns.Add(p.Name, p.PropertyType);
}
}
然后我嘗試在 dt 數據表中創建一行,如下所示:
DataRow dr = dt.NewRow();
Type t = ex.GetType();
for (int i = 0; i <= dt.Columns.Count; i++)
{
t.InvokeMember(dt.Columns[i].ColumnName, System.Reflection.BindingFlags.SetProperty, null, ex, new object[] { dt.Columns[i].ColumnName });
}
...在執行和跟蹤時,InvokeMember 成功迭代了 CountryCode、Currency 和 DataSourceCode 列,但是隨后 - 當它到達 DaysHoursId - 拋出“System.MissingMethodException:'Method MarketApi.Core.Entitites.Exchange.DaysHoursId'未找到'異常。
任何關於我做錯了什么的見解將不勝感激!
它會拋出DaysHoursId ,因為它是 class Exchange 的第一個非字符串屬性。 問題是您將屬性名稱也設置為它們的值。
適用於CountryCode、Currency、DataSourceCode ,它們都需要一個字符串值。 但在DaysHoursId上崩潰。 活頁夾查找實際上不存在的名稱/簽名set_DaysHoursId(string)
的字符串屬性設置方法。
您寧願在該循環中分配值:
DataRow dr = dt.NewRow();
Type t = ex.GetType();
//TODO fill your data in here
object [] values = new [dt.Columns.Count] { /* "de", "EUR", ... */};
for (int i = 0; i <= dt.Columns.Count; i++)
{
t.InvokeMember(dt.Columns[i].ColumnName, System.Reflection.BindingFlags.SetProperty, null, ex,
new [] { values [i] });
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.