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类中检查必填字段。对于不重复的代码,我想分别检查头部控制和通用数据控制。但我不知道,如何获得HeadRequiredFields方法的参考?

"RootApiModel<object> item" 

"RootApiModel<T> item"

我收到无法转换警告

 public static class RequiredFieldsControl
{
    private static void HeadRequiredFields(RootApiModel<object> item)
    {
        if (string.IsNullOrEmpty(item.@event))
            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");
    }
}

HeadRequiredFields可能看起来像这样:

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

这会将<T>限制为引用类型,因此不允许使用值类型。

最新更新