2016-12-06 69 views
0

我有一個使用mvc c#和typescript代碼的web應用程序,我有一個C#枚舉和描述。如何從一個typescript 1.8代碼迭代C#枚舉描述屬性

MyEnum 
{ 
    [First Value] FirstValue, 
    [Second Value] SecondValue 
} 

我需要重複的是C#枚舉,並得到說明添加到打字稿一個陣列 - 我怎樣才能做到這一點?

編輯 既然我在工作中,我可以發佈完整的代碼 - 我的問題與打字稿有關。

命名空間作業{

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using Serenity.ComponentModel; 
using System.ComponentModel; 


[EnumKey("Order.Status")] 
public enum Status 
{ 
    [Description("Order Active")] 
    OrderActive = 1, 
    [Description("Order Complete")] 
    OrderComplete = 2 
} 

}

如何重複上述打字稿枚舉?

打字稿代碼如下:

export class OrderStatusEditor extends Serenity.Select2Editor<any, any> { 

    private OrderStatusList: string[]; 
    private statName: Status; 

    constructor(container: JQuery) { 
     super(container, null); 

    // Iterate the C# Enum Status 
    for (var key in statName) 
    this.addOption("key1", "Text 1"); 

} 

在上面的 「文本1」 是枚舉狀態 Description屬性 「命令激活」,而不是Status.OrderActive。

+0

你不能做到這一點香草JavaScript,因此你不能這樣做它在TypeScript中。您必須在服務器上收集描述並將它們發送給客戶端。你如何去做這取決於你。 – krillgar

+0

@krillgar - 這就是爲什麼我有一個打字稿標籤,並特別要求如何在打字稿中做到這一點。請查看我正在嘗試執行此操作的代碼示例。 – Ken

+1

這就是我要說的。當您處於TypeScript代碼中時,您無權訪問服務器端代碼。你的TypeScript變成了香草JavaScript,它在瀏覽器中執行。這段代碼沒有任何線索,也不關心在服務器上執行什麼代碼,更不用說它使用的是什麼語言。就像我說的,你需要在C#中完成這些工作,並將值發送到TypeScript。你無法在那裏找到那些信息。 – krillgar

回答

0

您應該更新您的代碼片段,以便它是有效的C#。從你的代碼中獲取一個真實的例子。還舉例說明你想要數組的內容,基於示例枚舉。

這聽起來像是一份Reflection的工作。您可以獲取枚舉的Type對象,然後發現您需要了解的所有內容,並生成數據以返回到您的客戶端(可能在本例中爲JSON數組)。

+0

我在工作,所以我發佈了一個真實的例子。 c#方面不是我所需要的 - 我以前從未使用過的打字稿是我需要代碼來迭代它的地方。 – Ken

+0

在你的TS代碼中說:'private statName:Status;' - Status的聲明是什麼樣的?它必須在TS中。你是用手寫的還是用C#自動生成的? –

+0

多數民衆贊成我的代碼寫作試圖找出這種打字機如何工作,看看我怎麼能從真正的枚舉得到屬性描述..。 – Ken

0

使用反射。希望這可以幫助。你的問題不具有打字稿的關係,取下吊牌,請

 private static string GetEnumDescription<TEnum>(TEnum item, string enumName) where TEnum: struct 
     { 
      Type type = item.GetType(); 

      var attribute = 
       type.GetField(item.ToString()) 
        .GetCustomAttributes(typeof (DescriptionAttribute), false) 
        .Cast<DescriptionAttribute>() 
        .FirstOrDefault(); 

      return attribute == null 
       ? enumName 
        .FirstCharToUpper() 
        .ToSeparatedWords() 
       : attribute.Description; 
     } 

而且方式來使用它

var eType = typeof (TEnum); 

foreach (TEnum eValue in Enum.GetValues(eType)) 
{ 
    var name = Enum.GetName(eType, eValue); 
    var descp = GetEnumDescription(eValue, name); 
} 
+0

請看這個問題的更新 - 你可以看到與打字稿的相關性與代碼,我顯示打字稿代碼文件,我試圖做到這一點。我需要在打字稿中迭代它。 – Ken