簡體   English   中英

C#如何在C#和Razor中訪問動態變量屬性

[英]C# How To Access Dynamic Variable Properties in C# and Razor

我有一個存儲在數據庫中的存儲過程的名稱(和幾個視圖)。 在運行時,我查詢數據庫,然后運行所需的查詢。 由於我不知道查詢的字段名稱,也沒有已知的對象來存儲結果,因此我使用動態變量

dynamic results = Respository.GetTableContents(); 
// not exactly the code but it conveys the point

該表將具有未知數量的字段,但在此示例中,字段名稱為

Id, FirstName, Lastname  //(this is what the table would be returning) 

// Normally stored to a list of the model type
List<Users> resultsFromTable = ...

生成的動態數據可以通過以下方式訪問

foreach(var r in result)
{
    string name = r.FirstName + " " + r.LastName;
    //.... Do something with the code, etc.
}

如果您知道屬性名稱,那就太好了。 我不知道屬性名稱。

如何在不知道屬性名稱的情況下訪問動態變量的數據?

我的主要目標是在視圖(剃刀)中使用它。

也許我錯誤地解決了這個問題,並且有更好的方法。 有什么想法嗎?

另一種選擇是使用System.Reflection 嘗試這個:

foreach (var r in results)
{
    string name, trimmedName = "";
    if (r.GetType() == typeof(ExpandoObject))
    { 
        name = ((IDictionary<string,object>)r).ToList()
            .Aggregate<KeyValuePair<string,object>, string>("", (s, p) =>
        {
            return s + " " + p.Value;
        });
        trimmedName = name.Trim();
    }
    else
    {
        PropertyInfo[] ps = r.GetType().GetProperties();
        name = ps.Aggregate<PropertyInfo, string>("", (s, p) =>
        {
            return s + " " + p.GetValue(r);
        });
        trimmedName = name.Trim();
    }
    // use the trimmedName 
    Console.WriteLine(trimmedName);
}

[編輯]根據@pwas的建議,以下是他的代碼的版本,該代碼具有改進的循環復雜性:

foreach (var r in results)
{
    ProcessResult(r);
}

其中ProcessResult有2個重載:

static void ProcessResult(ExpandoObject r)
{
    string name, trimmedName = "";
    name = ((IDictionary<string, object>)r).ToList()
        .Aggregate<KeyValuePair<string, object>, string>("", (s, p) =>
        {
            return s + " " + p.Value;
        });
    trimmedName = name.Trim();
    FurtherProcess(trimmedName);
}

static void ProcessResult(object r)
{
    string name, trimmedName = "";
    PropertyInfo[] ps = r.GetType().GetProperties();
    name = ps.Aggregate<PropertyInfo, string>("", (s, p) =>
    {
        return s + " " + p.GetValue(r);
    });
    FurtherProcess(trimmedName);
}

private static void FurtherProcess(string trimmedName)
{
    Console.WriteLine(trimmedName);
}

這是改進之處:

Type        Maintainability     Cyclomatic
            Index               Complexity
Program     54                  24
// After code optimization
Program     69                  16

暫無
暫無

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

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