[C#] 객체를 int로 캐스팅하는 더 좋은 방법

이것은 아마도 사소한 일이지만 더 좋은 방법은 생각할 수 없습니다. C #에서 객체가되는 변형을 반환하는 COM 객체가 있습니다. 내가 이것을 int로 가져올 수있는 유일한 방법은

int test = int.Parse(string.Format("{0}", myobject))

더 깔끔한 방법이 있습니까? 감사



답변

몇 가지 옵션이 있습니다.

  • (int)— 캐스트 연산자. 개체가 이미 상속 계층 구조의 특정 수준에서 정수이거나 암시 적 변환이 정의 된 경우 작동합니다.

  • int.Parse()/int.TryParse() — 알 수없는 형식의 문자열에서 변환합니다.

  • int.ParseExact()/int.TryParseExact() — 특정 형식의 문자열에서 변환

  • Convert.ToInt32() — 알 수없는 유형의 객체를 변환합니다. 명시 적 및 암시 적 변환 또는 IConvertible 구현이 정의 된 경우이를 사용합니다.

  • as int?— “?”에 유의하십시오. as연산자는 참조 형식에 대해서만, 그리고 내가 사용 그래서 “?” 를 의미합니다 Nullable<int>. ” as“연산자는 다음과 같이 작동 Convert.To____()하지만 TryParse()오히려 생각 합니다. 변환이 실패하면 예외를 던지기보다는 Parse()반환 null합니다.

이 중 (int)객체가 실제로 박스형 정수인지 선호 합니다. 그렇지 않으면 Convert.ToInt32()이 경우에 사용 하십시오.

이것은 매우 일반적인 답변입니다. Darren Clark의 답변에 약간의주의를 기울이고 싶습니다. 왜냐하면 여기 에서 구체적인 내용을 다루는 것이 좋지만 늦게 와서 아직 투표하지 않았기 때문입니다. 그는 어쨌든 “inted answer”에 대한 내 투표를 얻습니다. 권장 (int), 실패하면 (int)(short)대신 작동 할 수 있음을 지적하고 실제 런타임 유형을 찾기 위해 디버거를 확인하도록 권장합니다.


답변

캐스트 (int) myobject 작동 해야 합니다.

이것이 잘못된 캐스트 예외를 제공하면 변형 유형이 VT_I4가 아니기 때문일 수 있습니다. 내 생각에 VT_I4가있는 변형은 boxed int로, VT_I2는 boxed short로 변환됩니다.

상자 값 유형에 캐스트를 수행 할 때 상자 유형에 캐스트하는 것만 유효합니다. 예를 들어, 반환 된 변형이 실제로 VT_I2이면 (int) (short) myObject작동합니다.

가장 쉽게 찾을 수있는 방법은 반환 된 객체를 검사하고 디버거에서 해당 유형을 살펴 보는 것입니다. 또한 interop 어셈블리에 반환 값이 표시되어 있는지 확인하십시오MarshalAs(UnmanagedType.Struct)


답변

Convert.ToInt32 (myobject);

이것은 myobject가 null 인 경우를 처리하고 예외를 throw하는 대신 0을 반환합니다.


답변

다음 Int32.TryParse과 같이 사용하십시오 .

  int test;
  bool result = Int32.TryParse(value, out test);
  if (result)
  {
     Console.WriteLine("Sucess");         
  }
  else
  {
     if (value == null) value = ""; 
     Console.WriteLine("Failure");
  }


답변

각 캐스팅 방법의 차이점을 나열하고 있습니다. 특정 유형의 주조 핸들이 있지만 그렇지 않습니다.

    // object to int
    // does not handle null
    // does not handle NAN ("102art54")
    // convert value to integar
    int intObj = (int)obj;

    // handles only null or number
    int? nullableIntObj = (int?)obj; // null
    Nullable<int> nullableIntObj1 = (Nullable<int>)obj; // null

   // best way for casting from object to nullable int
   // handles null 
   // handles other datatypes gives null("sadfsdf") // result null
    int? nullableIntObj2 = obj as int?; 

    // string to int 
    // does not handle null( throws exception)
    // does not string NAN ("102art54") (throws exception)
    // converts string to int ("26236")
    // accepts string value
    int iVal3 = int.Parse("10120"); // throws exception value cannot be null;

    // handles null converts null to 0
    // does not handle NAN ("102art54") (throws exception)
    // converts obj to int ("26236")
    int val4 = Convert.ToInt32("10120"); 

    // handle null converts null to 0
    // handle NAN ("101art54") converts null to 0
    // convert string to int ("26236")
    int number;

    bool result = int.TryParse(value, out number);

    if (result)
    {
        // converted value
    }
    else
    {
        // number o/p = 0
    }


답변

아마 Convert.ToInt32 일 것 입니다.

두 경우 모두 예외를 조심하십시오.


답변

var intTried = Convert.ChangeType(myObject, typeof(int)) as int?;