1

所以我有 ac# 类,上面有三个属性。

public class ClassA
{
    public bool IsBool1;
    public bool IsBool2;
    public bool IsBool3;
}

我有一种方法可以执行以下操作。

public void MethodA()
{
    ClassA c = GetCurrentClassA();
    c.IsBool1 = !c.IsBool1;
    ClassADataAccess.Update(c);
    this.BindClassADetails(c);
}

现在为了避免为其他两个属性编写 MethodA,有没有办法编写一个可以处理所有三个属性的方法?

可能是这样的?

public void UpdateAndBind(bool value)
{
    ClassA c = GetCurrentClassA();

    ///what to do here to set the property?

    ClassADataAccess.Update(c);
    this.BindClassADetails();
}
4

3 回答 3

1

回应您的评论:

这可以很好地工作,我只是好奇是否有办法告诉方法要设置传入对象的哪个属性。——克里斯·惠森亨特

有一种使用反射的方法:

    // using a generic method, you can specify the name of the property you want to set, 
    // the instance you want it set on, and the value to set it to...
    private T SetProperty<T>(T instance, string propertyName, object value)
    {
        Type t = typeof(T);
        PropertyInfo prop = t.GetProperty(propertyName);
        prop.SetValue(instance, value, null);
        return instance;
    }

现在......您可能想要使用 try/catch,也可能在以各种方式使用它之前检查传递的内容,以确保它不会突然爆炸......但通常,最简单地说,这就是你的方式做吧。祝你好运!

于 2012-09-16T21:52:17.600 回答
1

可以使用 Func 委托作为输入参数来完成。

首先,您需要使用属性,而不是字段:

public class ClassA
{
    public bool IsBool1 { get; set; }
    public bool IsBool2 { get; set; }
    public bool IsBool3 { get; set; }
}

然后你需要两个 Func 委托作为输入参数:

public ClassB
{
     public void UpdateAndBind(Func<ClassA, bool> getProp, Func<ClassA, bool, ClassA> setProp)
    {
        ClassA c = GetCurrentClassA();

        // What to do here to set the property?
        setProp(c, getProp(c));

        ClassADataAccess.Update(c);
        this.BindClassADetails(c);
    }
    ...
}

最后,用法如下所示:

static void Main(string[] args)
{
    ClassB classB = new ClassB();
    classB.UpdateAndBind(classA => classA.IsBool1, (classA, value) => { classA.IsBool1 = !value; return classA; });
    classB.UpdateAndBind(classA => classA.IsBool2, (classA, value) => { classA.IsBool2 = !value; return classA; });
    classB.UpdateAndBind(classA => classA.IsBool3, (classA, value) => { classA.IsBool3 = !value; return classA; });
}
于 2019-09-03T10:11:12.270 回答
0

GetCurrentClassA方法添加参数以便在那里指定所需的值怎么样?

public void MethodA()
{
    ClassA c = GetCurrentClassA(true, false, true);
    ClassADataAccess.Update(c);
    this.BindClassADetails(c);
}
于 2012-09-16T20:02:46.610 回答