开发者

C# Extension Method that reads an object as a specified type

开发者 https://www.devze.com 2023-04-11 23:14 出处:网络
I find the following scenario quite often: You have a string that you want to convert to an integer. But first you must check:

I find the following scenario quite often: You have a string that you want to convert to an integer.

But first you must check:

        string sId = null;

        if (!string.IsNullOrEmpty(sId))
        {
            return int.Parse(sId);
        }
        else
        {
            return -1;
        }

But what i want is to be able to do this:

sId.As<int>(-1)

So what i can do is write an exension method as follows:

public static class ObjectExtensions
{
    public static T As<T>(this object instance, T defaultValue)
    {
        try
        {
      开发者_JAVA技巧      if (instance != null)
            {
                return (T)Convert.ChangeType(instance, typeof(T));
            }
        }
        catch
        {                
        }
        return defaultValue;
    }
}

My question is does anyone have a suggestion that this is a good approach?

Is there anything built into .NET 3.5 or up that is built in that can do this?


Instead of catching the thrown exception, I would check if the type can be changed. In this question a CanChangeType method is described.


Couldn't you just use Int.TryParse instead?

string str = null;
int i;
bool result = Int32.TryParse(str, out i);


I think it's OK if your program needs it but I'd like to make a few style suggestions:

  • call it Convert<T> rather than As<T>
  • let the defaultValue take a default
  • Consider not making it be an extension method. I know extension methods are great and all but I think there's something overly promiscuous about extension methods whose first argument is System.Object. The problem is you hit the autocomplete key in your IDE and you start finding a bunch of weird extension methods on every single object you use in your program. Converting isn't that common an operation, so I think I'd prefer MyUtil.Convert

So I'd slightly change your signature at least to:

public static class MyUtil {
  public static T Convert<T>(object instance, T defaultValue=default(T)) 

* EDIT *

I might also propose the alternative syntax

public static bool TryConvert<T>(object instance, out T result) {

* EDIT 2 *

And I might propose taking IConvertible rather than object, just to narrow the interface a little bit:

  public static T Convert<T>(IConvertible instance, T defaultValue=default(T)) {
     ...
  }
  public static bool TryConvert<T,U>(T instance, out U result) where T : IConvertible {
     ...
  }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号