首頁  >  文章  >  後端開發  >  .NET MyMVC框架如何為方法賦值的教學課程

.NET MyMVC框架如何為方法賦值的教學課程

Y2J
Y2J原創
2017-05-17 11:28:051763瀏覽

用過反射的人都知道,呼叫一個方法很簡單,但如何給一個【不知簽名】的方法準備傳入參數呢?
下面就來回答這個問題,請接著看GetActionCallParameters的實現過程:

private static object[] GetActionCallParameters(HttpContext context, ActionDescription action)
{    if( action.Parameters == null || action.Parameters.Length == 0 )        return null;    object[] parameters = new object[action.Parameters.Length];    for( int i = 0; i < action.Parameters.Length; i++ ) {        ParameterInfo p = action.Parameters[i];        if( p.IsOut )            continue;        if( p.ParameterType == typeof(NameValueCollection) ) {            if( string.Compare(p.Name, "Form", StringComparison.OrdinalIgnoreCase) == 0 )
                parameters[i] = context.Request.Form;            else if( string.Compare(p.Name, "QueryString", StringComparison.OrdinalIgnoreCase) == 0 )
                parameters[i] = context.Request.QueryString;            else if( string.Compare(p.Name, "Headers", StringComparison.OrdinalIgnoreCase) == 0 )
                parameters[i] = context.Request.Headers;            else if( string.Compare(p.Name, "ServerVariables", StringComparison.OrdinalIgnoreCase) == 0 )
                parameters[i] = context.Request.ServerVariables;
        }        else{            Type paramterType = p.ParameterType.GetRealType();            // 如果参数是简单类型,则直接从HttpRequest中读取并赋值            if( paramterType.IsSimpleType() ) {                object val = ModelHelper.GetValueByKeyAndTypeFrommRequest(
                                                context.Request, p.Name, paramterType, null);                if( val != null )
                    parameters[i] = val;
            }            else {                // 自定义的类型。首先创建实例,然后给所有成员赋值。
                // 注意:这里不支持嵌套类型的自定义类型。                object item = Activator.CreateInstance(paramterType);                ModelHelper.FillModel(context.Request, item, p.Name);
                parameters[i] = item;
            }
        }
    }    return parameters;
}

要理解這段程式碼還要從前面的【查找Action的過程】說起,在那個階段,可以獲取一個Action的描述,具體在框架內部表示為ActionDescription類型:

internal sealed class ActionDescription : BaseDescription{    public ControllerDescription PageController; //为PageAction保留    public MethodInfo MethodInfo { get; private set; }    public ActionAttribute Attr { get; private set; }    public ParameterInfo[] Parameters { get; private set; }    public bool HasReturn { get; private set; }    public ActionDescription(MethodInfo m, ActionAttribute atrr) : base(m)
    {        this.MethodInfo = m;        this.Attr = atrr;        this.Parameters = m.GetParameters();        this.HasReturn = m.ReturnType != ReflectionHelper.VoidType;
    }
}

建構子的第三行程式碼中,我就可以得到這個方法的所有參數情況。
然後,我在就可以在GetActionCallParameters方法中,循環每個參數的定義,為它們賦值。
這段程式碼也解釋了前面所說的只支援4種NameValueCollection集合的原因。

注意了,我在取得每個參數的類型時,是使用了下面的語句:

Type paramterType = p.ParameterType.GetRealType();

實際上,ParameterType就已經反映了參數的類型,為什麼不直接使用它呢?
答:因為【可空泛型】的原因。這個類型我們需要特殊的處理。
例如:如果某個參數是這樣宣告的: int? id 
那麼,即使在QueryString中包含id這樣一個參數,我也不能直接轉成int? 使用這種類型,必須得到它的【實際類型】。
GetRealType()是個擴充方法,它就專門完成這個功能:

/// <summary>
/// 得到一个实际的类型(排除Nullable类型的影响)。比如:int? 最后将得到int/// </summary>
/// <param name="type"></param>
/// <returns></returns>public static Type GetRealType(this Type type)
{    if( type.IsGenericType )        return Nullable.GetUnderlyingType(type) ?? type;    else
        return type;
}

如果某個參數的類型是一個自訂的類型,框架會先建立實例(呼叫無參的建構子),然後給它的Property, Field賦值。

注意了:自訂的型別,一定要提供一個無參的建構子。

為自訂類型的實例填入資料成員的程式碼如下:

internal static class ModelHelper{    public static readonly bool IsDebugMode;    static ModelHelper()
    {        CompilationSection configSection = 
                    ConfigurationManager.GetSection("system.web/compilation") as CompilationSection;        if( configSection != null )
            IsDebugMode = configSection.Debug;
    }    /// <summary>
    /// 根据HttpRequest填充一个数据实体。    /// 这里不支持嵌套类型的数据实体,且要求各数据成员都是简单的数据类型。    /// </summary>
    /// <param name="request"></param>
    /// <param name="model"></param>    public static void FillModel(HttpRequest request, object model, string paramName)
    {        ModelDescripton descripton = ReflectionHelper.GetModelDescripton(model.GetType());        object val = null;        foreach( DataMember field in descripton.Fields ) {            // 这里的实现方式不支持嵌套类型的数据实体。
            // 如果有这方面的需求,可以将这里改成递归的嵌套调用。            val = GetValueByKeyAndTypeFrommRequest(
                                request, field.Name, field.Type.GetRealType(), paramName);            if( val != null )
                field.SetValue(model, val);
        }
    }    /// <summary>
    /// 读取一个HTTP参数值。这里只读取QueryString以及Form    /// </summary>
    /// <param name="request"></param>
    /// <param name="key"></param>
    /// <returns></returns>    public static string GetHttpValue(HttpRequest request, string key)
    {        string val = request.QueryString[key];        if( val == null )
            val = request.Form[key];        return val;
    }    
    public static object GetValueByKeyAndTypeFrommRequest(                        HttpRequest request, string key, Type type, string paramName)
    {        // 不支持复杂类型        if( type.IsSimpleType() == false )            return null;        string val = GetHttpValue(request, key);        if( val == null ) {            // 再试一次。有可能是多个自定义类型,Form表单元素采用变量名做为前缀。            if( string.IsNullOrEmpty(paramName) == false ) {
                val = GetHttpValue(request, paramName + "." + key);
            }            if( val == null )                return null;
        }        return SafeChangeType(val.Trim(), type);
    }    public static object SafeChangeType(string value, Type conversionType)
    {        if( conversionType == typeof(string) )            return value;        if( value == null || value.Length == 0 )            // 空字符串根本不能做任何转换,所以直接返回null            return null;        try {            // 为了简单,直接调用 .net framework中的方法。
            // 如果转换失败,则会抛出异常。            return Convert.ChangeType(value, conversionType);
        }        catch {            if( IsDebugMode )                throw;            // Debug 模式下抛异常            else
                return null;    // Release模式下忽略异常(防止恶意用户错误输入)        }
    }
}

在載入資料給自訂的資料類型實例之前,需要先知道這個實例物件有哪些屬性以及字段,這個過程的程式碼如下:

/// <summary>
/// 返回一个实体类型的描述信息(全部属性及字段)。/// </summary>
/// <param name="type"></param>
/// <returns></returns>public static ModelDescripton GetModelDescripton(Type type)
{    if( type == null )        throw new ArgumentNullException("type");    
    string key = type.FullName;    ModelDescripton mm = (ModelDescripton)s_modelTable[key];    if( mm == null ) {        List<DataMember> list = new List<DataMember>();
        (from p in type.GetProperties(BindingFlags.Instance | BindingFlags.Public)         select new PropertyMember(p)).ToList().ForEach(x=>list.Add(x));
        (from f in type.GetFields(BindingFlags.Instance | BindingFlags.Public)         select new FieldMember(f)).ToList().ForEach(x => list.Add(x));
        mm = new ModelDescripton { Fields = list.ToArray() };
        s_modelTable[key] = mm;
    }    return mm;
}

在拿到一個類型的所有屬性以及字段的描述資訊後,就可以通過循環的方式,根據這些數據成員的名字去QueryString,Form讀取所需的資料了。

【相關推薦】

1. 特別推薦#:「php程式設計師工具箱」V0.1版本下載

2. ASP免費影片教學

3.  入門級的.NET MVC 實例

4. MyMVC方塊尋找Action的流程詳解

#5. .NET MyMVC架構執行Action的流程詳解

#6. .NET MyMVC框架處理傳回值的教學

以上是.NET MyMVC框架如何為方法賦值的教學課程的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn