1 回答
TA贡献1868条经验 获得超4个赞
我的想法是使用 lambda 表达式以简单直观的方式访问属性信息数据(使用 IntelliSense 支持和所有可用的重构)。演示该方法的代码如下。
using System;
using System.Linq.Expressions;
using System.Reflection;
namespace ConsoleAppTest2
{
class Program
{
static void Main(string[] args)
{
var myModel = new MyModel();
var cmb = ConsoleModelBuilder<MyModel>.RequestFromComsole(myModel)
.FillProp(x=>x.MethodName)
.FillProp(x => x.Birthday);
Console.ReadLine();
}
}
internal class MyModel
{
public int MethodName { get; set; }
public DateTime Birthday { get; set; }
}
internal class ConsoleModelBuilder<T>
{
public T Model { get; private set; }
public static ConsoleModelBuilder<T> RequestFromComsole(T obj)
{
return new ConsoleModelBuilder<T>() { Model = obj };
}
public ConsoleModelBuilder<T> FillProp<TProperty>(Expression<Func<T, TProperty>> propertyLambda)
{
PropertyInfo info = GetPropertyInfo(Model, propertyLambda);
Console.WriteLine($"Hi, Please enter {info.Name} value as {info.PropertyType.Name}:");
//Code to parse console input and fill property of Model
return this;
}
public PropertyInfo GetPropertyInfo<TSource, TProperty>(
TSource source,
Expression<Func<TSource, TProperty>> propertyLambda)
{
Type type = typeof(TSource);
MemberExpression member = propertyLambda.Body as MemberExpression;
if (member == null)
throw new ArgumentException(string.Format(
"Expression '{0}' refers to a method, not a property.",
propertyLambda.ToString()));
PropertyInfo propInfo = member.Member as PropertyInfo;
if (propInfo == null)
throw new ArgumentException(string.Format(
"Expression '{0}' refers to a field, not a property.",
propertyLambda.ToString()));
if (type != propInfo.ReflectedType &&
!type.IsSubclassOf(propInfo.ReflectedType))
throw new ArgumentException(string.Format(
"Expression '{0}' refers to a property that is not from type {1}.",
propertyLambda.ToString(),
type));
return propInfo;
}
}
}
访问 PropertyInfo 的核心方法来自 StackOverflow 问题Retrieving Property name from lambda expression。
- 1 回答
- 0 关注
- 150 浏览
添加回答
举报