IT박스

메소드의 리턴 유형을 일반으로 만들려면 어떻게합니까?

itboxs 2020. 6. 13. 19:32
반응형

메소드의 리턴 유형을 일반으로 만들려면 어떻게합니까?


이 메소드를 일반화하여 문자열, bool, int 또는 double을 리턴 할 수있는 방법이 있습니까? 지금은 문자열을 반환하지만 구성 값으로 "true"또는 "false"를 찾을 수 있으면 예를 들어 bool을 반환하고 싶습니다.

    public static string ConfigSetting(string settingName)
    {  
         return ConfigurationManager.AppSettings[settingName];
    }

다음과 같은 일반적인 방법으로 만들어야합니다.

public static T ConfigSetting<T>(string settingName)
{  
    return /* code to convert the setting to T... */
}

그러나 호출자 는 예상되는 유형을 지정해야합니다. 그런 다음 Convert.ChangeType모든 관련 유형이 지원된다고 가정하여을 사용할 수 있습니다 .

public static T ConfigSetting<T>(string settingName)
{  
    object value = ConfigurationManager.AppSettings[settingName];
    return (T) Convert.ChangeType(value, typeof(T));
}

나는이 모든 것이 좋은 생각이라고 전적으로 확신하지는 않습니다.


당신은 사용할 수 있습니다 Convert.ChangeType():

public static T ConfigSetting<T>(string settingName)
{
    return (T)Convert.ChangeType(ConfigurationManager.AppSettings[settingName], typeof(T));
}

이를 수행하는 방법에는 여러 가지가 있습니다 (우선 순위에 따라 OP의 문제에 따라 나열 됨)

  1. 옵션 1 : 직선 접근 -하나의 일반 함수를 사용하지 않고 예상되는 각 유형에 대해 여러 함수를 작성하십시오.

    public static bool ConfigSettingInt(string settingName)
    {  
         return Convert.ToBoolean(ConfigurationManager.AppSettings[settingName]);
    }
    
  2. 옵션 2 : 멋진 변환 방법을 사용하지 않으려는 경우 -값을 객체로 캐스트 한 다음 일반 유형으로 캐스트하십시오.

    public static T ConfigSetting<T>(string settingName)
    {  
         return (T)(object)ConfigurationManager.AppSettings[settingName];
    }
    

    참고- 캐스트가 유효하지 않은 경우 오류가 발생합니다 (귀하의 경우). 유형 캐스팅에 대해 잘 모르면 옵션 3으로 이동하십시오.

  3. 옵션 3 : 형식 안전성이 있는 일반-형식 변환을 처리하는 일반 함수를 만듭니다.

    public static T ConvertValue<T,U>(U value) where U : IConvertible
    {
        return (T)Convert.ChangeType(value, typeof(T));
    } 
    

    참고 -T는 예상되는 유형입니다. 여기서 where 제약 조건을 참고하십시오 (U의 유형은 I에서 변환 가능해야 오류에서 벗어날 수 있습니다)


메소드의 리턴 값 유형을 호출하는 동안 메소드에 전달하는 일반 유형으로 변환해야합니다.

    public static T values<T>()
    {
        Random random = new Random();
        int number = random.Next(1, 4);
        return (T)Convert.ChangeType(number, typeof(T));
    }

해당 메서드를 통해 반환되는 값에 대해 형식을 지정할 수있는 형식을 전달해야합니다.

전달할 수있는 제네릭 형식으로 형식을 지정할 수없는 값을 반환하려면 코드를 변경하거나 메서드의 반환 값으로 형식을 지정할 수있는 형식을 전달해야합니다. 따라서이 방법은 권장되지 않습니다.


함수를 작성하고 일반 매개 변수로 put 매개 변수를 전달하십시오.

 public static T some_function<T>(T out_put_object /*declare as Output object*/)
    {
        return out_put_object;
    }

아래 코드를 시도하십시오 :

public T? GetParsedOrDefaultValue<T>(string valueToParse) where T : struct, IComparable
{
 if(string.EmptyOrNull(valueToParse))return null;
  try
  {
     // return parsed value
     return (T) Convert.ChangeType(valueToParse, typeof(T));
  }
  catch(Exception)
  {
   //default as null value
   return null;
  }
 return null;
}

 private static T[] prepareArray<T>(T[] arrayToCopy, T value)
    {
        Array.Copy(arrayToCopy, 1, arrayToCopy, 0, arrayToCopy.Length - 1);
        arrayToCopy[arrayToCopy.Length - 1] = value;
        return (T[])arrayToCopy;
    }

I was performing this throughout my code and wanted a way to put it into a method. I wanted to share this here because I didn't have to use the Convert.ChangeType for my return value. This may not be a best practice but it worked for me. This method takes in an array of generic type and a value to add to the end of the array. The array is then copied with the first value stripped and the value taken into the method is added to the end of the array. The last thing is that I return the generic array.

참고URL : https://stackoverflow.com/questions/9808035/how-do-i-make-the-return-type-of-a-method-generic

반응형