Trong .NET lớp Type dùng để biểu thị sự khai báo của: định nghĩa của lớp, mảng, enum, interface ... Muốn lấy Type của đối tượng object, dùng phương thức object.GetType(), nó trả về một Type - cho biết thông tin kiểu (class, interface, enum ...) của đối tượng.

Lớp Type với các phương thức, thuộc tính của nó, nó trở thành lớp cơ bản của kỹ thuật Reflection trong .Net, ví dụ một vài phương thức:

  • GetMethods() trả về tên các phương public
  • GetProperties() trả về tên các thuộc tính pulic của lớp
  • GetFields() lấy các trường public
  • GetEvents() lấy các sự kiện
  • GetProperty(String) lấy đối tượng PropertyInfo biểu thị thuộc tính với tên chỉ ra
  • ...





1. Code C# , Lấy giá trị của variable trong model theo tên variable name
Test thử online : https://coderseditor.com



using System;
                    
public class Program
{
    public static void Main()
    {
        var p = new Person {
            Name = "Mark",
            AddressDetail = new Address {
                Street = "First St.",
                CountryDetail = new Country {
                    CountryName = "USA"
                }
            }
        };
        var nested1 = GetPropertyValue(p, "Name");
        var nested2 = GetPropertyValue(p, "AddressDetail.Street");
        var nested3 = GetPropertyValue(p, "AddressDetail.CountryDetail.CountryName");
        Console.WriteLine(nested1);
        Console.WriteLine(nested2);
        Console.WriteLine(nested3);
    }
    
    
    
    public static object GetPropertyValue(object src, string propName)
    {
        if (src == nullthrow new ArgumentException("Value cannot be null.""src");
        if (propName == nullthrow new ArgumentException("Value cannot be null.""propName");
        
        if(propName.Contains("."))//complex type nested
        {
            var temp = propName.Split(new char[] { '.' }, 2);
            return GetPropertyValue(GetPropertyValue(src, temp[0]), temp[1]);
        }
        else
        {
            var prop = src.GetType().GetProperty(propName);
            return prop != null ? prop.GetValue(src, null) : null;
        }
    }
}



public class Person{
    public string Name { getset;}
    public Address AddressDetail { getset;}
}

public class Address{
    public string Street { getset;}
    public Country CountryDetail { getset;}
}

public class Country{
    public string CountryName { getset;}
}




Kết quả trả về :
Volvo Mark First St. USA




2. Lấy giá trị của variable trong model theo tên variable name
Regex là các mẫu (pattern) thay vì các chuỗi cụ thể


using System;
using System.Text.RegularExpressions;
                    
public class Program
{
    public static void Main()
    {
        var str = "{Name = \"'AddressDetail.ThisIsString'\", Number = 'AddressDetail.ThisIsNumber'}";

        //string str = "Would \"you\" like to have responses to your \"questions\" sent to you via email?";
        Random _random = new Random();  

        //Console.WriteLine(_random.Next(1000));  

        var reg = new Regex("\'.*?\'");
        var matches = reg.Matches(str);
        foreach (var item in matches)
        {
            Console.WriteLine(item.ToString());
            //vi du ve gan value 
            str = str.Replace(item.ToString(), _random.Next(10000).ToString());
        }

        //Ket qua cuoi cung
        Console.WriteLine(str);

    }
   
    
    
    public static object GetPropertyValue(object src, string propName)
    {
        if (src == nullthrow new ArgumentException("Value cannot be null.""src");
        if (propName == nullthrow new ArgumentException("Value cannot be null.""propName");
        
        if(propName.Contains("."))//complex type nested
        {
            var temp = propName.Split(new char[] { '.' }, 2);
            return GetPropertyValue(GetPropertyValue(src, temp[0]), temp[1]);
        }
        else
        {
            var prop = src.GetType().GetProperty(propName);
            return prop != null ? prop.GetValue(src, null) : null;
        }
    }
}




Kết quả trả về :
Ban đầu
{Name = 'Name', Street = 'AddressDetail.Street',CountryName = 'AddressDetail.CountryDetail.CountryName',Cars='AddressDetail.CountryDetail.Cars'}
Kết thúc {Name = 'Mark', Street = 'First St.',CountryName = 'VietNam',Cars='Volvo,BMW,Ford,Mazda,'}