문제

ASP.NET GridView를 익명 유형 모음에 묶었습니다.

RowDatabound 이벤트 핸들러에서 익명 유형의 속성 중 하나를 참조하려면 어떻게해야합니까?

나는 이미 익명 유형을 다음과 같이 캐스팅하는 방법을 이미 알고 있습니다.

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        var AnonObj = Cast(e.Row.DataItem, 
          new { StringProperty = "", BoolProperty = false, IntProperty = 0 });

        if (AnonObj.BoolProperty)
        {
            e.Row.Style.Add(HtmlTextWriterStyle.Color, "Red");
        }
    }
}


T Cast<T>(object obj, T type)
{
    return (T)obj;
}

나는 그것이 효과가 있지만 대부분이 지저분하다고 말할 것이라고 생각합니다. 실제 코드에는 3 개 이상의 속성이 있으며 익명 유형의 속성을 추가하거나 재정렬 할 때마다 두 곳에서 코드를 업데이트해야합니다.

e.row.dataitem이 특정 유형의 특정 속성을 가지고 있다고 말하고 객체에 그 값을 부여하도록 강제 (클래스 생성 외에) 더 좋은 방법이 있습니까?

도움이 되었습니까?

해결책

당신이 사용하는 방식 (예제)은 지저분하고 매우 취성 - i 진짜 권장하지 마십시오 (속성을 추가하거나 다른 순서로 이름을 지정하면 끊어집니다). 더 나은 접근 방식은 투영에서 자신의 명명 된 유형을 사용하는 것입니다.

다른 팁

반사를 사용하여 살펴보십시오.

예시:

object o = e.Row.DataItem;
Type t = o.GetType();
PropertyInfo pi = t.GetProperty("StringProperty");
if (pi != null && pi.PropertyType == typeof(string))
{
  // the property exists!
  string s = pi.GetValue(o, null) as string;
  // we have the value
  // insert your code here
  // PROFIT!  :)
}

오류 확인 및 최적화는 독자에게 연습으로 남았습니다.

A better way would be to create a type to handle this so you don't have to do all that casting to use the anonymous type.

What I do is ... for example,

string Name = (string)DataBinder.Eval(dataItem.DataItem, "Name");

... but this is in a listview ItemDataBound event handler. Thought it might be useful for someone.

No, I don't believe there's any better way than this. The C# guys don't really support using anonymous types outside of local method scope (i.e. here you have an anonymous type attached to your Row object.)

The usual suggestion would be to make a real class instead.

The method you're using to cast the anonymous object (while very cool) is a hack. It works simply because the C# compiler is smart enough to only create one instance of the Anonymous Class for the entire app if the Properties are the same. So there really is no benefit in using anonymous types, since a class is being created behind the scenes anyway. Yes, you can hack it, you can use reflection, but seriosuly, why bother? What benefit is there to using Anonymous types in this case?

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top