简体   繁体   中英

Extension method for a type writing the <T>

In .NET I could get a List<PropertyInfo> using the following

obj.GetType().GetProperties().ToList();

in order to make it nicer I did

public static IList<PropertyInfo> GetPropertyInfo<T>(this T obj)
{
    return obj.GetType().GetProperties().ToList();
}

but something uglier came up, which is

obj.GetPropertyInfo<Wrapper>();

but I was wondering how can I avoid the <T> the way they avoid it?

Why can't it just be

obj.GetPropertyInfo();

There is no reason why you cannot drop the T generic parameter from your extension method, because you are not using that generic parameter anywhere!

So, please write:

public static IList<PropertyInfo> GetPropertyInfo(this object obj)
{
    return obj.GetType().GetProperties().ToList();
}

Why do you need a method with generic type argument? Couldn't your method just be like following?

public static IList<PropertyInfo> GetPropertyInfo(this object obj)
{
    return obj.GetType().GetProperties().ToList();
}

The question is why you made this method generic, if call GetType of object instance. Just remove generic.

public static IList<PropertyInfo> GetPropertyInfo(this T obj)
{
    return obj.GetType().GetProperties().ToList();
}

You can change your method to take parameter of System.Type type and remove the GetType() invocation:

public static IList<PropertyInfo> GetPropertyInfo(this Type obj)
{
    return obj.GetProperties().ToList();
}

In this case you could use it as follows:

var propertyInfos = typeof(MyType).GetPropertyInfo();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM