code

생성 후 익명 유형에 속성 추가

codestyles 2020. 8. 22. 08:55
반응형

생성 후 익명 유형에 속성 추가


익명 개체를 사용하여 내 Html 특성을 일부 도우미 메서드에 전달합니다. 소비자가 ID 속성을 추가하지 않은 경우 도우미 메서드에 추가하고 싶습니다.

이 익명 개체에 속성을 추가하려면 어떻게해야합니까?


이 방법을 확장하려는 경우 :

public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, object routeValues);

Khaja의 Object 확장이 작동 할 것이라고 확신하지만 RouteValueDictionary를 만들고 routeValues ​​개체를 전달하고 Context에서 추가 매개 변수를 추가 한 다음 개체 대신 RouteValueDictionary를 사용하는 ActionLink 오버로드를 사용하여 반환하면 더 나은 성능을 얻을 수 있습니다.

이것은 트릭을 수행해야합니다.

    public static MvcHtmlString MyLink(this HtmlHelper helper, string linkText, string actionName, object routeValues)
    {
        RouteValueDictionary routeValueDictionary = new RouteValueDictionary(routeValues);

        // Add more parameters
        foreach (string parameter in helper.ViewContext.RequestContext.HttpContext.Request.QueryString.AllKeys)
        {
            routeValueDictionary.Add(parameter, helper.ViewContext.RequestContext.HttpContext.Request.QueryString[parameter]);
        }

        return helper.ActionLink(linkText, actionName, routeValueDictionary);
    }

다음 확장 클래스는 필요한 것을 얻을 수 있습니다.

public static class ObjectExtensions
{
    public static IDictionary<string, object> AddProperty(this object obj, string name, object value)
    {
        var dictionary = obj.ToDictionary();
        dictionary.Add(name, value);
        return dictionary;
    }

    // helper
    public static IDictionary<string, object> ToDictionary(this object obj)
    {
        IDictionary<string, object> result = new Dictionary<string, object>();
        PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(obj);
        foreach (PropertyDescriptor property in properties){
            result.Add(property.Name, property.GetValue(obj));
        }
        return result;
    }
}

여기에서 익명 유형을 의미한다고 가정합니다 new { Name1=value1, Name2=value2}. 그렇다면 운이 좋지 않습니다. 익명 유형은 고정되고 컴파일 된 코드라는 점에서 일반 유형입니다. 자동 생성됩니다.

당신이 할 있는 것은 글을 쓰는 new { old.Name1, old.Name2, ID=myId }것이지만 그것이 정말로 당신이 원하는 것인지 모르겠습니다. 상황에 대한 자세한 내용 (코드 샘플 포함)이 이상적입니다.

또는 항상 ID가 있는 컨테이너 개체 와 나머지 속성이 포함 된 다른 개체를 만들 수 있습니다 .


public static string TextBox(this HtmlHelper html, string value, string labelText, string textBoxId, object textBoxHtmlAttributes, object labelHtmlAttributes){}

이것은 텍스트 상자에 있어야하고 레이블이 참조해야하는 id 값을 허용합니다. 소비자가 이제 textBoxHtmlAttributes에 "id"속성을 포함하지 않는 경우 메서드는 잘못된 레이블을 만듭니다.

I can check through reflection if this attribute is added in the labelHtmlAttributes object. If so, I want to add it or create a new anonymous object that has it added. But because I can't create a new anonymous type by walking through the old attributes and adding my own "id" attribute, I'm kind of stuck.

A container with a strongly typed ID property and then an anonymous typed "attributes" property would require code rewrites that don't weigh up to the "add an id field" requirement.

Hope this response is understandable. It's the end of the day, can't get my brains in line anymore..

참고URL : https://stackoverflow.com/questions/233711/add-property-to-anonymous-type-after-creation

반응형