2017-05-23 37 views
-2

我有模型來獲取頭字段和泛型類型的數據。C#如何獲得泛型類引用的方法

public class RootApiModel<T> where T : class 
{ 
    public string @event { get; set; } 
    public string timestamp { get; set; } 
    public string token { get; set; } 
    public string signature { get; set; } 
    public int status { get; set; } 
    public T data { get; set; } 
} 

我說,我檢查在RequiredFieldsControl必填字段class.For代碼是不重複的問題,我想檢查頭控制和通用數據控制separately.But我不知道,怎麼能我得到HeadRequiredFields方法的參考?

"RootApiModel<object> item" 

"RootApiModel<T> item" 

我越來越不能轉換警告

public static class RequiredFieldsControl 
{ 
    private static void HeadRequiredFields(RootApiModel<object> item) 
    { 
     if (string.IsNullOrEmpty([email protected])) 
      throw new Exception("Event Alanı Zorunludur"); 

     if (string.IsNullOrEmpty(item.timestamp)) 
      throw new Exception("Timestamp Alanı Zorunludur"); 

     if (string.IsNullOrEmpty(item.token)) 
      throw new Exception("Token Alanı Zorunludur"); 

     if (string.IsNullOrEmpty(item.signature)) 
      throw new Exception("Signature Alanı Zorunludur"); 

     if (item.status <= 0) 
      throw new Exception("Status Alanı Zorunludur"); 
    } 
    public static void BuildingControl(RootApiModel<BuildingApiModel> buildingItem) 
    { 
     HeadRequiredFields(buildingItem); 

     if (buildingItem.data.ReferenceID<=0) 
      throw new Exception("BuildingReferenceID Alanı Zorunludur"); 

     if (string.IsNullOrEmpty(buildingItem.data.BuildingName)) 
      throw new Exception("BuildingName Alanı Zorunludur"); 
    } 

    public static void BlockControl(RootApiModel<BlockApiModel> blockItem) 
    { 
     HeadRequiredFields(blockItem); 

     if (blockItem.data.BuildingReferenceID <= 0) 
      throw new Exception("BuildingReferenceID Alanı Zorunludur"); 

     if (blockItem.data.BlockReferenceID <= 0) 
      throw new Exception("BlockReferenceID Alanı Zorunludur"); 

     if (string.IsNullOrEmpty(blockItem.data.BlockName)) 
      throw new Exception("BlockName Alanı Zorunludur"); 
    } 

} 
+0

使你的'HeadRequiredFields'通用。將''添加到方法的定義中,並使用它來代替''。 –

+1

「不起作用」不是有效的問題描述。這是什麼意思?例外?意外的結果? – HimBromBeere

+0

好,我編輯 –

回答

3

HeadRequiredFields或許應該是這個樣子:

private static void HeadRequiredFields<T>(RootApiModel<T> item) where T : class 

這將限制<T>是引用類型,因此值類型將不被允許。

+0

我做了你所說的,但現在我得到這個警告「類型'T'必須是參考類型,以便在通用類型或方法中使用 它作爲參數'T' 'RootApiModel '「在HeadRequiredFields (RootApiModel item)上的項目 –

相關問題