cast anonymous type to an interface?

前端 未结 3 868
梦如初夏
梦如初夏 2020-12-09 09:09

This doesn\'t seem to be possible? So what is the best work-around? Expando / dynamic?

public interface ICoOrd {
    int x { get; set; }
    int y { get; s         


        
相关标签:
3条回答
  • 2020-12-09 09:29

    The best "workaround" is to create and use a normal, "named" type that implements the interface.

    But if you insist that an anonymous type be used, consider using a dynamic interface proxy framework like ImpromptuInterface.

     var myInterface =  new { x = 44, y = 55 }.ActLike<ICoOrd>();
    
    0 讨论(0)
  • 2020-12-09 09:45

    No, anonymous types never implement interfaces. dynamic wouldn't let you cast to the interface either, but would let you just access the two properties. Note that anonymous types are internal, so if you want to use them across assemblies using dynamic, you'll need to use InternalsVisibleTo.

    0 讨论(0)
  • 2020-12-09 09:50

    I know this is an old question and answers but I stumbled on this on this looking to do exactly the same thing for some unit tests. I then occurred to me that I am already doing something like this using Moq (facepalm).

    I do like the other suggestion for ImpromptuInterface but I am already using Moq and feel like it having a larger following (that is opinion and not fact) will be more stable and supported longer.

    so for this case would be something like

    public interface ICoOrd
    {
        int X { get; set; }
        int Y { get; set; }
    }
    
    public class Sample
    {
    
        public void Test()
        {
            var aCord = new Mock<ICoOrd>();
            aCord.SetupGet(c => c.X).Returns(44);
            aCord.SetupGet(c => c.Y).Returns(55);
    
            var a = aCord.Object;
        }
    }
    

    EDIT: just adding another way to mock the cord, started doing it this way and like it a little better.

    public void AnotherTest()
    {
        var aCord = Mock.Of<ICoOrd>(c => c.X == 44 && c.Y == 55);
        //do stuff with aCord
    }
    
    0 讨论(0)
提交回复
热议问题