Any inline object. AsType <T>

I have an input line such as

"x=y|a=b|c=10" etc 

which is converted to dynamic, which I use as

 dynamic d = getDynamicFromStringAbove(); someFunc( daAsType<int>() ) 

where AsType is an extension method defined as

  public static T AsType<T>(this string o){ return (T) Convert.ChangeType(o, typeof(T)); } 

QUESTION - Is there something within the framework that provides this already

  object.AsType<T>() 

?? It seems to be very convenient with dynamic types, so I guess it there, and I don't want to add code that already exists

+4
source share
2 answers

No, there is no built-in method that works like your extension method. I think the framework developers wanted people to know that they need to perform an explicit operation to parse a string, etc.

By the way, can I suggest changing the AsType method to use TypeConverter instead of Convert.ChangeType ? It is a little more powerful and flexible. For example, it works best for converting enum values ​​to the appropriate types.

 public enum Foo {A,B,C} ... TypeDescriptor.GetConverter(typeof(Foo)).ConvertFrom("A"); // Yields Foo.A Convert.ChangeType("A", typeof(Foo)); // Throws exception 

See this answer for more details.

Update

I must indicate:

  • This approach really makes sense if your .AsType() method takes object as its parameter. Since in the question you take string , and how is s.AsType<int>() preferable to int.Parse(s) ?
  • Since you cannot use the extension method syntax for the dynamic value, the code provided in the question will not actually work if pouring da into a string value.
+2
source

You may be looking for the as keyword, although it only works for link types.

You should write an expression like:

 var instanceOfT = a as T; 

If a can be converted to T , then it will contain a valid strongly typed link of this type. Otherwise, a will be a null reference.

Other examples of what you can and cannot do with as ...

 dynamic d; d = "test!"; // this will work and get a valid String reference var stringInstance = d as String; d = 1; // next line generates a compiler error as Int32 (int) isn't a reference type var integerInstance = d as Int32; // and this compiles, but results in a null reference as d isn't a String anymore var anotherString = d as String; 
+2
source

Source: https://habr.com/ru/post/1402505/


All Articles