c#如何使用myclass.object1.child作为一个整体参数?

时间:2017-02-01 13:11:59

标签: c#

这是我的班级:

InfoClass info = new InfoClass()

现在,我在另一个文件中创建此类的实例,例如:

        info.pull();
        info.serverBuild.status = "checking";
        info.push();

然后我使用pull和push来更新一些值:

info.Update(serverBuild.status, "checking"); //instead of above 3 lines

我想要的是创建一些辅助方法来更频繁地使用它。像这样:

  frames = getVideoFrames();
  stichPair(frames[1], frames[0], panorama[0]);
    for (int i = 2; i < SIZE; i++)
    {
        stichPair(frames[i], panorama[i - 2], panorama[i - 1]);
        printf("%d\n", i);
    }

    cvNamedWindow(windowsName1, 1);
    on_trackbar(index, 0);
    createTrackbar("MyTrackbar:", windowsName1, &index, SIZE - 2, on_trackbar);

2 个答案:

答案 0 :(得分:1)

写一个扩展名:

public static class Extensions
{
    public static void Update<T>(this T info, Action<T> action) where T : InfoClass
    {
        info.pull();
        action(info);
        info.push();
    }
}

然后像这样使用它:

info.Update(x=>{x.serverBuild.status = "test";});

答案 1 :(得分:0)

您可以在InfoClass中创建方法,让我们说:

public void Update(string name, object value)
{
    pull(); // pull from here
    // split name into "path like"
    string[] path = name.Split('.', StringSplitOptions.RemoveEmptyEntries);
    // set current path reference
    object current = this;
    for(int i = 0; i < path.Length - 1; i++)
    {
        string way = path[i];
        // reassign reference till the pre-last element
        current = current.GetType().GetProperty(way, BindingFlags.Instance | BindingFlags.Public).GetValue(current);
    }
    // set the new value 
    current.GetType().GetProperty(path[path.Length - 1], BindingFlags.Instance | BindingFlags.Public).SetValue(current, value);
    push(); // push from here
}

然后您几乎可以按照自己的意愿使用它,而是info.Update(serverBuild.status, "checking");您将info.Update("serverBuild.status", "checking");

Check this online