动态创建接口成员 [英] Dynamically create members of interface

查看:95
本文介绍了动态创建接口成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个View,它实现了一个接口.

I have a View, that implements an interface.

我正在尝试对此进行单元测试,但这很无聊...

I'm trying to unit test this, but it gets boring...

声明是:

public interface IView : IBaseView
{
    TextBox ClientId { get; set; }
    TextBox ClientName { get; set; }
    Button SaveClient { get; set; }
    Button NextClient { get; set; }
    Button PreviousClient { get; set; }
    Button DiscardChanges {get;set;}
    bool ReadOnly { get; set;  }
    ListBox MyLittleList { get; set; }
}

    [Test]
    public void FirstSteps()
    {
        var sessionFactory = Substitute.For<ISessionFactory>();
        var session = Substitute.For<ISession>();
        var statelessSession = Substitute.For<IStatelessSession>();
        sessionFactory.OpenSession().Returns(session);
        sessionFactory.OpenStatelessSession().Returns(statelessSession);

        var view = Substitute.For<IView>();

        view.ClientId = new System.Windows.Forms.TextBox();
        view.ClientName = new System.Windows.Forms.TextBox();
        view.DiscardChanges = new System.Windows.Forms.Button();
        view.MyLittleList = new System.Windows.Forms.ListBox();
        view.NextClient = new System.Windows.Forms.Button();
        view.PreviousClient = new System.Windows.Forms.Button();
        view.ReadOnly = false;
        view.SaveClient = new System.Windows.Forms.Button();
    }

我是否有观点可以动态地做到这一点?

Is there a view for me to dynamically do that?

将View传递给方法,该方法将验证其中的内容并自动调用构造函数并对其进行设置?

Pass the View to a method, that will verify what is there and automatically call a constructor on and set it?

推荐答案

我不确定您要查找的内容,但这也许会有所帮助吗?:

Im not fully sure what you are looking for but maybe this might help a bit?:

public static void SetData<T>(T obj)
{
  foreach (var property in typeof(T).GetProperties())
    if (property.CanWrite && property.GetIndexParameters().Length == 0)
    {
      object val = null;

      //// Optionally some custom logic if you like:
      //if (property.PropertyType == typeof(string))
      //    val = "Jan-Peter Vos";
      //else

        val = Activator.CreateInstance(property.PropertyType);

      property.SetValue(obj, val, null);
    }
}

[Test]
public void FirstSteps()
{
  // .. Your code ..

  SetData(view);
}

这篇关于动态创建接口成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆