Skip to main content
 首页 » 编程设计

接受字符串参数的C#函数: How to refactor to use something strongly typed

2024年02月24日28三少

我有这个工作正常的 C# 代码,它抓取任意两个字段并将它们放入下拉列表的列表中:

var myDDL = GetDDLValues<Product>( myContact, "contactid", "companyname"); 

我希望它在字符串之外的其他东西中获取两个字符串参数。这真的很不错:

GetDDLValues<Product>( myContact, p => p.contactid, p => p.companyname) 

这是它调用的代码(由 sweko 反射(reflect),谢谢!):

private object GetProperty(object obj, string propertyName) 
{ 
    PropertyInfo pi = obj.GetType().GetProperty(propertyName); 
    object value = pi.GetValue(obj, null); 
    return value; 
} 
 
public  IList<DDLValues> GetDDLValues<T>(IList<T> objectListToMap,  
                         string textProperty, string valueProperty) 
{    
    if( objectListToMap != null && objectListToMap.Count > 0) 
    { 
        Mapper.CreateMap< T, DDLValues>() 
              .ForMember( dest => dest.text,  
                           opt => opt.MapFrom(src => textProperty)) 
              .ForMember( dest => dest.value,  
                           opt => opt.MapFrom(src => valueProperty)); 
        return Mapper.Map<IList<T>, IList<DDLValues>>(objectListToMap); 
    } 
    else 
    { 
        return null; 
    } 
} 

请您参考如下方法:

从字符串构建动态查询:

public class Product  
{  
    public long ID { get; set; }  
    public string Name { get; set; }  
    public DateTime Date { get; set; }  
}  
 
 
static void Main(string[] args)  
{  
    List<Product> products = (from i in Enumerable.Range(1, 10)  
                          select new Product { ID = i, Name = "product " + i, Date = DateTime.Now.AddDays(-i) }).ToList();  //the test case  
 
    const string SortBy = "Date";  // to test you can change to "ID"/"Name"  
 
    Type sortType = typeof(Product).GetProperty(SortBy).PropertyType;     // DateTime  
    ParameterExpression sortParamExp = Expression.Parameter(typeof(Product), "p");    // {p}  
    Expression sortBodyExp = Expression.PropertyOrField(sortParamExp, SortBy);   // {p.DateTime}  
    LambdaExpression sortExp = Expression.Lambda(sortBodyExp, sortParamExp);   //   {p=>p.DateTime}  
    var OrderByMethod = typeof(Enumerable).GetMethods().Where(m => m.Name.Equals("OrderBy") && m.GetParameters().Count() == 2).FirstOrDefault().MakeGenericMethod(typeof(Product), sortType);  
    var result = OrderByMethod.Invoke(products, new object[] { products, sortExp.Compile() });  
}