Using System.Reflection to Get a Method's Full Name

后端 未结 8 1374
执念已碎
执念已碎 2020-12-13 06:00

I have a class that look like the following:

public class MyClass
{

...

    protected void MyMethod()
    {
    ...
    string myName = System.Reflection.M         


        
相关标签:
8条回答
  • 2020-12-13 06:47

    Thanks for the posts above, they helped me to create a strong type binding system for MVC 4 HTMLHelpers as follows.

     public static MvcHtmlString StrongTypeBinder(this HtmlHelper htmlhelper, Expression<Func<object, string>> SomeLambda)
        {
            var body = SomeLambda.Body;
            var propertyName = ((PropertyInfo)((MemberExpression)body).Member).Name;
            HtmlString = @"
                <input type='text' name='@Id' id='@Id'/>
                ";
            HtmlString = HtmlString.Replace("@Id", propertyName);
            var finalstring = new MvcHtmlString(HtmlString);
            return finalstring;
    
        }
    

    To use the code above in any CSHTML View:

    @Html.StrongTypeBinder(p=>Model.SelectedDate)
    

    This allows me to bind any property in a ViewModel to any HTML element type I want. In the example above, I an binding the name field for the selected data posted back after user makes selection. The viewmodel after the post back automatically shows the selected value.

    0 讨论(0)
  • 2020-12-13 06:50

    You could look at the ReflectedType of the MethodBase you get from GetCurrentMethod, i.e.,

    MethodBase method = System.Reflection.MethodBase.GetCurrentMethod();
    string methodName = method.Name;
    string className = method.ReflectedType.Name;
    
    string fullMethodName = className + "." + methodName;
    
    0 讨论(0)
提交回复
热议问题