1
如何將if(propType.PropertyType == typeof(string))和if(propType.PropertyType == typeof(int))更改爲更動態的內容?創建不同類型的表達式
private void button2_Click(object sender, EventArgs e)
{
var lista = _pessoas.AsQueryable();
if (textBox2.Text != "")
{
var param = Expression.Parameter(typeof(Pessoa), "x");
var propriedade = Expression.Property(param, textBox2.Text);
var propType = typeof(Pessoa).GetProperties().FirstOrDefault(x => x.Name == textBox2.Text);
if (propType.PropertyType == typeof(string))
{
lista = lista.Where(Expression.Lambda<Func<Pessoa, bool>>(
Expression.Equal(
propriedade,
Expression.Constant(textBox3.Text)
), param));
}
else
{
if (propType.PropertyType == typeof(int))
{
lista = lista.Where(Expression.Lambda<Func<Pessoa, bool>>(
Expression.Equal(
propriedade,
Expression.Constant(int.Parse(textBox3.Text))
), param));
}
else
{
throw new NotImplementedException();
}
}
}
dataGridView1.DataSource = lista.ToList();
}
我不認爲你可以。但是,您可以擺脫'else'的大括號,並簡單地使用'else if(propType.PropertyType == typeof(int))' – Brad 2010-10-22 12:45:35