سؤال

هل من الممكن إنشاء نموذج نماذج لنوع عام؟ على سبيل المثال، إذا كان لدي نوع

public class MyType<T>

هل هناك أي طريقة لإنشاء موثق نموذج مخصص سيعمل لأي نوع من mytype؟

شكرا، ناثان

هل كانت مفيدة؟

المحلول

إنشاء ModelBinder، تجاوز BindModel، والتحقق من النوع والقيام بما تحتاج إلى القيام به

public class MyModelBinder
    : DefaultModelBinder {

    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {

         if (HasGenericTypeBase(bindingContext.ModelType, typeof(MyType<>)) { 
             // do your thing
         }
         return base.BindModel(controllerContext, bindingContext);
    }
}

اضبط النموذج الخاص بك على الإعداد الافتراضي في Global.asax

protected void Application_Start() {

        // Model Binder for My Type
        ModelBinders.Binders.DefaultBinder = new MyModelBinder();
    }

يتحقق من مطابقة قاعدة عامة

    private bool HasGenericTypeBase(Type type, Type genericType)
    {
        while (type != typeof(object))
        {
            if (type.IsGenericType && type.GetGenericTypeDefinition() == genericType) return true;
            type = type.BaseType;
        }

        return false;
    }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top