Home > other >  How to send a property type to generic method
How to send a property type to generic method

Time:01-30

I have a generic method which is responsible for reading a type.

 public List<GetDomainNameViewModel> GetDomainName<T>()
    {
        List<GetDomainNameViewModel> getDomainNameViewModels= new List<GetDomainNameViewModel>();

        var propertyInfos = typeof(T).GetProperties();

        for (int i = 0; i < propertyInfos.Length; i  )
        {
         Type type = Type.GetType(propertyInfos[i].DeclaringType.Name);

        /*Recursive mode*/
        var model2 = GetDomainName<type>();

        /*Recursive mode*/

            if (propertyInfos[i].CustomAttributes.Count() > 0)
            {
                var attrs = propertyInfos[i].GetCustomAttributes(true);
                foreach (var attr in attrs)
                {
                    JsonConverterAttribute rangeAttribute = attr as JsonConverterAttribute;
                    if (rangeAttribute != null)
                    {
                        var attProp = rangeAttribute.ConverterParameters;
                        var attpropList = attProp.FirstOrDefault().ToString().Split(';');

                        foreach (var item in attpropList)
                        {
                            if (item.StartsWith("Range"))
                            {
                              //  [Newtonsoft.Json.JsonConverter(typeof(ESBJsonConverter), "Range(1::100)=>6; NonEmptyString=>1313;Length(:16)=>1114")]
                                GetDomainNameViewModel model = new GetDomainNameViewModel();

                                /*get min value*/
                                int endIndex = item.IndexOf(':'), startIndex = item.IndexOf('(')   1;
                                int length = endIndex - startIndex;
                                string extracted = item.Substring(startIndex, length);
                                /*Endget min value*/

                                /*get max value*/
                                int endMaxIndex = item.IndexOf(')'), startMaxIndex = item.IndexOf(':', item.IndexOf(':'))   1;
                                int lengthMax = endMaxIndex - startMaxIndex;
                                string extractedMax = item.Substring(startMaxIndex   1, lengthMax - 1);
                                /*Endget max value*/
                                /*get error code*/
                                string errorCode = item.Substring(item.IndexOf('>')   1, (item.Length - 1) - item.IndexOf('>'));
                                /*get error code*/
                
                                model.FieldName = propertyInfos[i].Name;
                                model.MinVal = extracted;
                                model.MaxVal = extractedMax;
                                model.ErrorCode = errorCode;


                                /*Set errorMessage*/
                                StringBuilder errorMessage = new StringBuilder(ErrorsDictionary.ErrorList[Convert.ToInt32(errorCode)]);
                                errorMessage.Replace("{0}", model.FieldName).Replace("{1}", model.MinVal).Replace("{2}", model.MaxVal).Replace("{3}", model.ErrorCode);

                                /*End Set errorMessage*/
                                model.ErrorMessage = errorMessage;

                                getDomainNameViewModels.Add(model);

                            }
                            else if (item.StartsWith("NonEmptyString"))
                            {
                                //[JsonConverter(typeof(ESBJsonConverter), "NonEmptyString=>3064")]
                                GetDomainNameViewModel model = new GetDomainNameViewModel();

                                /*get error code*/
                                string errorCode = item.Substring(item.IndexOf('>')   1, (item.Length - 1) - item.IndexOf('>'));
                                /*get error code*/

                                model.FieldName = propertyInfos[i].Name;
                                model.ErrorCode = errorCode;


                                /*Set errorMessage*/
                                StringBuilder errorMessage = new StringBuilder(ErrorsDictionary.ErrorList[Convert.ToInt32(errorCode)]);
                                errorMessage.Replace("{0}", model.FieldName).Replace("{1}", model.ErrorCode);

                                /*End Set errorMessage*/
                                model.ErrorMessage = errorMessage;

                                getDomainNameViewModels.Add(model);

                            }
                            else if (item.StartsWith("Length"))
                            {
                                // [JsonConverter(typeof(ESBJsonConverter), "Length(1:16)=>1194;")]
                                GetDomainNameViewModel model = new GetDomainNameViewModel();

                                /*get error code*/
                                string errorCode = item.Substring(item.IndexOf('>')   1, (item.Length - 1) - item.IndexOf('>'));
                                /*get error code*/

                                /*get min value*/
                                int startIndex = item.IndexOf('(')   1;
                                int endIndex = item.IndexOf(':');
                                int length = endIndex - startIndex;
                                string extracted = item.Substring(startIndex, length);
                                /*Endget min value*/

                                /*get max value*/
                                int startMaxIndex = item.IndexOf(':', item.IndexOf(':')) ;
                                int endMaxIndex = item.IndexOf(')');
                                int lengthMax = endMaxIndex - startMaxIndex;
                                string extractedMax = item.Substring(startMaxIndex   1, lengthMax-1 );
                                /*Endget max value*/


                                model.FieldName = propertyInfos[i].Name;
                                model.MinVal = extracted;
                                model.MaxVal = extractedMax;
                                model.ErrorCode = errorCode;


                                /*Set errorMessage*/
                                StringBuilder errorMessage = new StringBuilder(ErrorsDictionary.ErrorList[Convert.ToInt32(errorCode)]);
                                errorMessage.Replace("{0}", model.FieldName).Replace("{1}", model.MinVal).Replace("{2}", model.MaxVal).Replace("{3}", model.ErrorCode);

                                /*End Set errorMessage*/
                                model.ErrorMessage = errorMessage;

                                getDomainNameViewModels.Add(model);


                            }

                            else if (item.StartsWith("NumericString"))
                            {
                           //     [JsonConverter(typeof(ESBJsonConverter), "NumericString=>1194;NonEmptyString=>1313;Length(8:8)=>1114;PDateTime(yyyyMMdd)=>1207")]
                                GetDomainNameViewModel model = new GetDomainNameViewModel();

                                /*get error code*/
                                string errorCode = item.Substring(item.IndexOf('>')   1, (item.Length - 1) - item.IndexOf('>'));
                                /*get error code*/                                  
                                model.FieldName = propertyInfos[i].Name;
                                    model.ErrorCode = errorCode;

                                /*Set errorMessage*/
                                StringBuilder errorMessage = new StringBuilder(ErrorsDictionary.ErrorList[Convert.ToInt32(errorCode)]);
                                errorMessage.Replace("{0}", model.FieldName).Replace("{1}", model.MinVal).Replace("{2}", model.MaxVal).Replace("{3}", model.ErrorCode);

                                /*End Set errorMessage*/
                                model.ErrorMessage = errorMessage;

                                getDomainNameViewModels.Add(model);


                            }
                            else if (item.StartsWith("PDateTime"))
                            {
                             //   [JsonConverter(typeof(ESBJsonConverter), "NumericString=>1194;NonEmptyString=>1313;Length(8:8)=>1114;PDateTime(yyyyMMdd)=>1207")]
                                GetDomainNameViewModel model = new GetDomainNameViewModel();

                                /*get error code*/
                                string errorCode = item.Substring(item.IndexOf('>')   1, (item.Length - 1) - item.IndexOf('>'));
                                /*get error code*/
                                model.FieldName = propertyInfos[i].Name;
                                model.ErrorCode = errorCode;

                                /*Set errorMessage*/
                                StringBuilder errorMessage = new StringBuilder(ErrorsDictionary.ErrorList[Convert.ToInt32(errorCode)]);
                                errorMessage.Replace("{0}", model.FieldName).Replace("{1}", model.ErrorCode);

                                /*End Set errorMessage*/
                                model.ErrorMessage = errorMessage;

                                getDomainNameViewModels.Add(model);


                            }


                        }

                    }
                }
            }
        }
        return getDomainNameViewModels;

    }

and I have a type here:

   public class Student
{
    public Student()
    {
    }

    [JsonConverter(typeof(ESBJsonConverter), "NonEmptyString=>1313")]
    public List<Student> Students { get; set; }
    [Newtonsoft.Json.JsonConverter(typeof(ESBJsonConverter), "range(1::100)=>6; nonemptystring=>1313;length(:16)=>1114")]
    public int studentid { get; set; }

    [Required]
    [Newtonsoft.Json.JsonConverter(typeof(ESBJsonConverter), "range(18::29)=>6; nonemptystring=>1313;length(:16)=>1114")]
    public string studentname { get; set; }

    [Range(10, 20)]
    public int age { get; set; }


    [JsonProperty(Required = Required.Always)]
    [JsonConverter(typeof(ESBJsonConverter), "NonEmptyString=>3064;")]

    public string iban { get; set; }

    [JsonProperty(Required = Required.Always)]
    [JsonConverter(typeof(ESBJsonConverter), "Length(1:16)=>1194;")]
   /public long Amount { get; set; }


    public List<long> Amounts { get; set; }


    [JsonProperty(Required = Required.Always)]
    [JsonConverter(typeof(ESBJsonConverter), "NumericString=>1194;NonEmptyString=>1313;Length(8:8)=>1114;PDateTime(yyyyMMdd)=>1207")]
    public string DueDate { get; set; }




    [JsonConverter(typeof(ESBJsonConverter), "NonEmptyString=>1313")]

    public List<long> Amounts { get; set; }



}

what is matter here is that I have a property Students in class student which is a complex type and I have to read all of custom attributes kind of recersivly in GetDomainName method.

I have some struggle here Type type = Type.GetType(propertyInfos[i].DeclaringType.Name);

        /*Recursive mode*/
        var model2 = GetDomainName<type>();

        /*Recursive mode*/

I get this error here :

type is a variable but used as a type

CodePudding user response:

When you specify a generic type parameter, you have to use data type. Anything that would not be valid when declaring a variable is not valid there either. Would you expect to be able to do this:

type myStudent = new type();

I would hope not, and for obvious reasons. The reasons are the same when calling a generic method. Just as when you declare a variable, you're providing an instruction to the compiler, so it should be obvious that information that is not known until run time is not valid. If you don't know the data type at compile time then you cannot call that method, plain and simple.

CodePudding user response:

Finally I figure out that I can achieve it this way and I changed my code in this fashion. I change sing of my method to :

public List<GetDomainNameViewModel> GetDomainName(Type T)

and calling it this way:

var x = propertyInfo.PropertyType;

                /*Recursive mode*/
                var model2 = GetDomainName(x);
  • Related