簡體   English   中英

反射,set.GetValue(context, null) 總是返回 null

[英]Reflection, set.GetValue(context, null) always return null

我正在嘗試通過反射從 object 獲取屬性。

public class CosmosDbSet<TEntity> : DbSet<TEntity> where TEntity : class, IEntity<string>
{
    public string Name { get; }
    //...
        );

}

public class SKCosmosDbContext : CosmosDBContext
{
    public CosmosDbSet<Item> Items { get; }

   public SKCosmosDbContext ()
   {
        Items = new CosmosDbSet<Item>(
            this,
            "Items"
        );
   }
    //...
}

public abstract class CosmosDBContext : DbContext
{
    public async Task EnsureContainersExistAsync()
    {
            var sets = GetType().GetProperties()
                .Where(pi => pi.PropertyType.IsGenericType
                    && pi.PropertyType.GetGenericTypeDefinition().Equals(typeof(CosmosDbSet<>))
                );
            foreach (var set in sets)
            {
                var value = set.GetValue(this, null); // => value is always null
                //...
            }
    }
}

public static class DbInitializer
{
    public async static Task InitializeAsync(IServiceProvider services, ILogger logger)
    {
        var dbContext = services.GetRequiredService<SKCosmosDbContext>();
        await dbContext.EnsureContainersExistAsync();
    }
}

如您所見,已找到來自 SKCosmosDbContext 的屬性 Items,但我無法訪問它。 描述

如何使用反射訪問屬性?

所以基本上我看到了使用.GetGenericTypeDefinition()調用的問題。 如果您進行更詳細的調試,您會看到它返回帶有下一個內容的可枚舉: 在此處輸入圖像描述

要獲得您想要的內容,您可以使用pi.PropertyType.GetGenericArguments()[0]並在 linq 查詢中使用它的返回值來等於它。 前任。 在此處輸入圖像描述

我使用虛擬類型只是為了舉例

您的問題也可能與此有關: 獲取通用列表的類型

TL;DR 示例在將查詢更改為:

var sets = db.GetType().GetProperties()
            .Where(pi => pi.PropertyType.IsGenericType
                && pi.PropertyType.GetGenericArguments()[0].Equals(typeof(...))
            );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM