Reflection (?) - Check for null or empty for each property/field in a class?
I have a simple class as such:
public class FilterParams
{
public string MeetingId { get; set; }
public int? ClientId { get; set; }
public string CustNum { get; set; }
public int AttendedAsFavor { get; set; }
public int Rating { get; set; }
public string Comments { get; set; }
public int Delete { get; set; }
}
How d开发者_如何转开发o I check for each of the property in the class, if they are not null (int) or empty/null (for string), then I'll convert and add that property's value to a List<string>
?
Thanks.
You can use LINQ to do that:
List<string> values
= typeof(FilterParams).GetProperties()
.Select(prop => prop.GetValue(yourObject, null))
.Where(val => val != null)
.Select(val => val.ToString())
.Where(str => str.Length > 0)
.ToList();
Not the finest approach but roughly:
Assuming obj
is the instance of your class:
Type type = typeof(FilterParams);
foreach(PropertyInfo pi in type.GetProperties())
{
object value = pi.GetValue(obj, null);
if(value != null && !string.IsNullOrEmpty(value.ToString()))
// do something
}
If you don't have a lot of such classes and not too many properties, the simplest solution is probably to write an iterator block that checks and converts each property:
public class FilterParams
{
// ...
public IEnumerable<string> GetValues()
{
if (MeetingId != null) yield return MeetingId;
if (ClientId.HasValue) yield return ClientId.Value.ToString();
// ...
if (Rating != 0) yield return Rating.ToString();
// ...
}
}
Usage:
FilterParams filterParams = ...
List<string> values = filterParams.GetValues().ToList();
PropertyInfo[] properties = typeof(FilterParams).GetProperties();
foreach(PropertyInfo property in properties)
{
object value = property.GetValue(SomeFilterParamsInstance, null);
// preform checks on value and etc. here..
}
Here's an example:
foreach (PropertyInfo item in typeof(FilterParams).GetProperties()) {
if (item != null && !String.IsNullOrEmpty(item.ToString()) {
//add to list, etc
}
}
Do you really need a reflection? Implementing a property like bool IsNull is a case for you? You can encapsulate it in interface like INullableEntity and implement in each class that need such a functionality, obviously if there are a lot of classes perhaps you have to stick with reflection.
精彩评论