interface ISample
{
int Id { get; set; }
}
public class MyClass : ISample
{
public int Id
{
get;
set;
}
public string Name { get; set; }
}
The above is a class which implements a interface ISample. Using generics i have added the below method to convert an object of given type to another type .
private TResult Sample<TSource, TResult>(TSource source)
where TSource : TResult
{
return (TResult)(source);
}
using Generics how do i achieve the reverse of the same that is given an ISample object i want to convert it back to MyClass object where ISample is the TSource and TResult is MyClass where TResult implements TSource.
You would simply have to switch from
where TSource : TResult
to
where TResult : TSource
ending up with code that might look like
private TResult ToInterface<TSource, TResult>(TSource source) where TSource : TResult
{
return source;
}
private TResult FromInterface<TSource, TResult>(TSource source) where TResult : TSource
{
return source as TResult;
}
Be aware that the FromInterface function will throw an InvalidCastException if the 'source' parameter is not of type TResult or does not inherit from TResult.
Edit:
See the answer by Lajos Arpad.
The compiler will not know in advance that you intend to do downcasting from TSource
to TResult
. You will need to cast your TSource
instance into something that is surely a superclass of TResult
, so you will need to cast TSource
to object
first:
(TResult)((object)source)
EDIT:
As pointed out in the comment section by @Zdeněk Jelínek, Eric Lippert has written a blog post about this.
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.