문제

이것은 간단하기를 바랍니다.

System.Web.Mvc.ViewPage< T > 클래스에 확장 메서드를 추가하고 싶습니다.

이 확장 방법은 어떻게 보일까요?

나의 첫 번째 직관적인 생각은 다음과 같습니다.

namespace System.Web.Mvc
{
    public static class ViewPageExtensions
    {
        public static string GetDefaultPageTitle(this ViewPage<Type> v)
        {
            return "";
        }
    }
}

해결책

일반적인 해결책은 이 답변.

System.Web.Mvc.ViewPage 클래스를 확장하는 구체적인 솔루션은 다음과 같습니다. 내 대답 아래는 에서 시작된 일반 솔루션.

차이점은 제네릭 유형의 메서드 선언과 제네릭 유형을 참조 유형으로 적용하는 명령문이 모두 필요한 특정 경우입니다.

도움이 되었습니까?

해결책

현재 컴퓨터에는 VS가 설치되어 있지 않지만 구문은 다음과 같습니다.

namespace System.Web.Mvc
{
    public static class ViewPageExtensions
    {
        public static string GetDefaultPageTitle<T>(this ViewPage<T> v)
        {
            return "";
        }
    }
}

다른 팁

감사합니다.그렇게 하면 오류가 발생했습니다.

'tmodel'유형은 일반 유형 또는 방법에서 매개 변수 'tmodel'으로 사용하려면 참조 유형이어야합니다.

그것은 나를 가리켰다 이 페이지, 다음과 같은 솔루션을 얻었습니다.

namespace System.Web.Mvc
{
    public static class ViewPageExtensions
    {
        public static string GetDefaultPageTitle<T>(this ViewPage<T> v) 
          where T : class
        {
            return "";
        }
    }
}

함수에 일반 유형 지정자가 필요합니다.

namespace System.Web.Mvc
{
    public static class ViewPageExtensions
    {
        public static string GetDefaultPageTitle<Type>(this ViewPage<Type> v)
        {
            return "";
        }
    }
}

편집하다:몇 초만에 놓쳤어요!

namespace System.Web.Mvc
{
    public static class ViewPageExtensions
    {
        public static string GetDefaultPageTitle<T>(this ViewPage<T> view)
            where T : class
        {
            return "";
        }
    }
}

또한 일반 유형에 "new()" 한정자를 추가해야 할 수도 있습니다(예:"여기서 T :class, new()"를 사용하여 T가 참조 유형(클래스)이면서 매개변수 없는 생성자를 갖도록 합니다.

글렌 블록 구현한 좋은 예가 있습니다. ForEach 확장 방법 IEnumerable<T>.

그의 블로그 게시물:

public static class IEnumerableUtils
{
    public static void ForEach<T>(this IEnumerable<T> collection, Action<T> action)
    {
        foreach(T item in collection)
            action(item);
    }
}

확장자가 지정된 유형에만 사용할 수 있도록하려면 처리 할 실제 유형을 지정하면됩니다.

뭔가...

public static string GetDefaultPageTitle(this ViewPage<YourSpecificType> v)
{
  ...
}

그러면 Intellisense는 일치하는 유형으로 ViewPage를 선언할 때만 확장 메서드를 표시합니다.

또한 System.Web.Mvc 네임스페이스를 사용하지 않는 것이 가장 좋습니다. usings 섹션에 네임스페이스를 포함할 필요가 없다는 점은 편리하지만 확장 기능에 대한 자체 확장 네임스페이스를 만드는 경우 유지 관리가 훨씬 더 쉽습니다.

Razor 뷰의 예는 다음과 같습니다.

public static class WebViewPageExtensions
{
    public static string GetFormActionUrl(this WebViewPage view)
    {
        return string.Format("/{0}/{1}/{2}", view.GetController(), view.GetAction(), view.GetId());
    }

    public static string GetController(this WebViewPage view)
    {
        return Get(view, "controller");
    }

    public static string GetAction(this WebViewPage view)
    {
        return Get(view, "action");
    }

    public static string GetId(this WebViewPage view)
    {
        return Get(view, "id");
    }

    private static string Get(WebViewPage view, string key)
    {
        return view.ViewContext.Controller.ValueProvider.GetValue(key).RawValue.ToString();
    }
}

일반 버전이 제네릭이 아닌 버전을 확장하므로 일반 버전을 사용할 필요가 없으므로 제네릭이 아닌 기본 클래스에 넣으면 완료됩니다. :)

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