C #에서 두 가지 유형을 어떻게 비교하는지 묻고 싶습니다.
내 시나리오는 다음과 같습니다.
Nullable<int> Rating;
int NeedCompareType;
이 두 가지를 비교할 때마다 잘못된 결과가 반환됩니다. 어쨌든 int
type이 두 줄에 모두 있기 때문에이 경우 true를 반환 할 수 있습니다.
내 비교 라인은 다음과 같습니다.
if(Rating.GetType() == NeedCompareType.GetType())
편집 : 실제로 이것은 내 프로그램 코드였습니다.
public object this[string propertyName]
{
get
{
PropertyInfo property = GetType().GetProperty(propertyName);
return property.GetValue(this, null);
}
set
{
PropertyInfo property = GetType().GetProperty(propertyName);
IFormatProvider culture = new System.Globalization.CultureInfo("fr-FR", true);
if (property.PropertyType == typeof(System.DateTime))
{
property.SetValue(this, Convert.ToDateTime(value, culture), null);
}
else if (property.PropertyType == typeof(int))
{
property.SetValue(this, Int32.Parse((string)value));
}
else
{
property.SetValue(this, value, null);
}
}
}
이 코드의 목적은 컨트롤러가 브라우저에서받는 값을 String 유형으로 캐스팅 한 다음 String 유형으로 적절한 unknown yet
모델 속성 유형 (이 경우 public Nullable<int> Rating { get; set; }
)으로 변환하는 것입니다.
내가 원할 때 알다시피 propertyName = "Rating"
, 두 번째 if 문을 실행해야하지만 typeof(int)
과 typeof(Nullable<int>)
다를 수 있기 때문에 실행되지 않습니다 .
내 하찮은 영어 실력에 죄송하다는 말씀을 드리고 싶습니다
실제로이 줄 :
if(Rating.GetType() == NeedCompareType.GetType())
항상 조건에 들어가거나 NullReferenceException
-를 던집니다. 왜냐하면 Rating.GetType()
will Rating
boxed Int32
또는 null 참조에 대한 상자 이기 때문 입니다 .
이제 비교 typeof(int)
하고 싶다고 말하면 다음을 typeof(Nullable<int>)
사용할 수 있습니다.
public bool SomewhatEqual(Type t1, Type t2)
{
return t1 == t2 ||
t1 == Nullable.GetUnderlyingType(t2) ||
Nullable.GetUnderlyingType(t1) == t2;
}
이제 실제로 관심이있는 코드를 보았으므로 각 속성을 nullable 형식이 아닌 것처럼 처리하려는 것처럼 들립니다. 간단합니다.
set
{
PropertyInfo property = GetType().GetProperty(propertyName);
Type type = property.GetType();
// Treat nullable types as their underlying types.
type = Nullable.GetUnderlyingType(type) ?? type;
// TODO: Move this to a static readonly field. No need to
// create a new one each time
IFormatProvider culture = new CultureInfo("fr-FR", true);
if (type == typeof(System.DateTime))
{
property.SetValue(this, Convert.ToDateTime(value, culture), null);
}
else if (type == typeof(int))
{
property.SetValue(this, Int32.Parse((string)value));
}
else
{
property.SetValue(this, value, null);
}
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다