Explicit generalization transformation

I implemented an explicit conversion from a string to an object called Foo.

So => Foo f = (Foo) "foo data"; work

I need to implement a function that passes a string to a common T, T in this case is the data type Foo.

public T Get<T>(object o){
      // this always return false
      if (typeof(T).IsAssignableFrom(typeof(String)))
      {
            // when i by pass the if above this throws invalid cast exception
            return (T)(object)str;
      }
      return null; 
}

// When I call this, it generated an error
// Invalid cast from 'System.String' to Foo
Foo myObj = Get<Foo>("another foo object"); 

// when I use the dynamic keyword it works but this is C# 4.0+ feature, my function is in the older framework
return (T)(dynamic)str;
+5
source share
5 answers

Reflection example:

class Program
{
    static void Main(string[] args)
    {           
        Foo myObj = TypeResolver.Get<Foo>("Foo data");            
    }
}

class TypeResolver
{
    public static T Get<T>(object obj)
    {
        if (typeof(T).CanExplicitlyCastFrom<string>())
        {                             
            return obj.CastTo<T>();
        }
        return default(T);
    }
}

public static class Extensions
{
    public static bool CanExplicitlyCastFrom<T>(this Type type)
    {
        if (type == null)
            throw new ArgumentNullException("type");

        var paramType = typeof(T);
        var castOperator = type.GetMethod("op_Explicit", 
                                        new[] { paramType });
        if (castOperator == null)
            return false;

        var parametres = castOperator.GetParameters();
        var paramtype = parametres[0];
        if (paramtype.ParameterType == typeof(T))
            return true;
        else
            return false;
    }

    public static T CastTo<T>(this object obj)
    {            
        var castOperator = typeof(T).GetMethod("op_Explicit", 
                                        new[] { typeof(string) });
        if (castOperator == null)
            throw new InvalidCastException("Can't cast to " + typeof(T).Name);
        return (T)castOperator.Invoke(null, new[] { obj });
    }
}
+2
source

Also see this answer from @Jon Skeet - and, in particular, a quote about IsAssignableFrom.

I do not think that this is possible the way you imagined it.

I would suggest you put an “front-end contract” on your Foo classes, and then let the generics do their work.

. - - , ...

class Factory 
{
    public static T Create<T, TVal>(TVal obj) where T : class, IFoo<TVal>, new()
    {
        return new T { Value = obj }; // return default(T);
    }
}
interface IFoo<TVal>
{
    TVal Value { get; set; }
}
class Foo : IFoo<string>
{
    public string Value { get; set; }
    public Foo() { }
}
// ...
public T Get<T, TVal>(TVal obj) where T : class, IFoo<TVal>, new()
{
    return Factory.Create<T, TVal>(obj);
}

- , have that luxury - ..
( )

Foo foo = Get<Foo, string>("another text");
+2

(object), /unbox ( IL: unbox-any) - . - (dynamic) (object), .

+1

, :

using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTestProject1
{
    [TestClass]
    public class UnitTest2
    {
        public T Get<T>(string str)
            where T : CanCastFromString<T>, ICanInitFromString, new()
        {
            return (T)str;
        }

        [TestMethod]
        public void Test()
        {
            var result = Get<Foo>("test");

            Assert.IsNotNull(result);
            Assert.IsInstanceOfType(result, typeof(Foo));
            Assert.AreEqual("test", result.Value);
        }
    }

    public class Foo : CanCastFromString<Foo>
    {
        public string Value { get; set; }

        public override void InitFromString(string str)
        {
            Value = str;
        }
    }

    public abstract class CanCastFromString<T> : ICanInitFromString
        where T : CanCastFromString<T>, ICanInitFromString, new()
    {
        public static explicit operator CanCastFromString<T>(string str)
        {
            var x = new T();
            x.InitFromString(str);
            return x;
        }

        public abstract void InitFromString(string str);
    }

    public interface ICanInitFromString
    {
        void InitFromString(string str);
    }
}

, , T string, abstract CanCastFromString, Get() .

0

, T , . , T.

namespace TestCast {
    class Program
    {
        public static T Get<T>(string o) where T : class
        {
            return o as T;
        }

        static void Main(string[] args)
        {
            Get<Breaker>("blah");
        }
    }
}

null, , Du, null, . . as .

0

All Articles