简体   繁体   English

将属性作为对象传递给方法

[英]Passing property as object to method

I would like to build a helper method which will take property as object to anonymous method. 我想建立一个将属性作为匿名方法对象的辅助方法。 This is just dummy code example to visualize problem not confront real solution which is way more complex and is not subject of this question. 这只是虚拟代码示例,用于可视化问题而不是实际解决方案,该解决方案更加复杂且不受此问题的影响。

Some reference code: 一些参考代码:

public class FooClass : SomeBaseClass {
    public string StringProperty { get; set; }

    public int IntProperty { get; set; }

    public DateTime DateTimeProperty { get; set; }

    public Object ComplexObjectProperty { get; set; }

    public FooClass() {
        this.FooMethod(this.StringProperty);
        this.FooMethod(this.IntProperty);
        this.FooMethod(this.DateTimeProperty);
        this.FooMethod(this.ComplexObjectProperty);
    }

    public void FooMethod<T>(T obj) {
        Func<bool> validateMethod = () => {
            if(obj is string) return string.IsNullOrEmpty(obj.ToString());
            return obj != null;
        };
        this.ValidateMethodsAggregate.Add(validateMethod);
    }
}

public class SomeBaseClass {
    protected IList<Func<bool>> ValidateMethodsAggregate = new List<Func<bool>>();

    public void ValidateAll() {
        foreach (var validateMethod in this.ValidateMethodsAggregate) {
            var result = validateMethod();
            // has errors and so on handling...
        }
    }
}

// Some simple code to show use case.
        var foo = new FooClass();
        foo.StringProperty = "new value";
        foo.IntProperty = 123;
        foo.ValidateAll(); // this will use "" , 0 instead of new values.

Use a function and a conditional operator with a private backing method 通过私有支持方法使用函数和条件运算符

        public FooClass()
        {
            this.FooMethod(() => StringProperty); // <- pass an accessor
        }
        public Func<bool> validateMethod;
        private void FooMethod<T>(Func<T> obj)
        {
            //validate method
            validateMethod = () => string.IsNullOrEmpty(obj()?.ToString());
        }

The usage would be 用法是

        var y = new FooClass();
        var resTrue = y.validateMethod();
        y.StringProperty = "Hi";
        var resFalse = y.validateMethod();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM