在集合中的对象上设置属性 [英] Setting a Property on an object in a Collection

查看:85
本文介绍了在集合中的对象上设置属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个抽象类...

public abstract class MyClass
{
    // other properties
    public bool IsTypeDefault {get;set;}
}

我还有许多其他类继承自 MyClass ,例如, MyClassA MyClassB MyClassC

I have a number of other classes that inherit from MyClass, say, MyClassA, MyClassB, MyClassC, etc.

我有一个定义为...的收集类。

And I have a collection class defined as ...

public class MyCollection : List<MyClass>
{
    public SetAsTypeDefault(MyClass item)
    {

    }
}

方法 SetAsTypeDefault 应该采用类型 MyClass 的对象,它将在集合中搜索相同类型的商品,在找到该值为true的任何商品上取消设置 IsTypeDefault ,然后将该商品设置为true匹配传入的参数。

The method SetAsTypeDefault should take an object of type MyClass, it will search the collection for a items of the same specific type, unset the IsTypeDefault on any item it finds where that value is true and then set it as true for the item that matches the passed in parameter.

想要的目的是阻止某人设置 IsTypeDefault 直接在集合的单个实例上获取值,我不知道该怎么做。

What I want is to stop someone from setting the IsTypeDefault value on an individual instance of the collection directly and I can't figure out how to do it.

我可以使 IsTypeDefault 只读,但是我不能从collection类设置它。我可以将其设置为 private set 并设置一个方法,但是该方法需要是公共的,以便可以从集合中调用。

I can make IsTypeDefault readonly, but then I can't set it from the collection class. I can set it as private set and have a method set it, but the method needs to be public to be callable from the collection.

我只想尝试执行此操作,因为访问该类的开发人员将完全无法控制我。我也无法审查他们的代码,并且我想确保他们不会弄乱事情。

I'm only going to the bother of trying to do this 'cos the devs accessing this class are going to be completely out of my control. Nor am I going to be able to review their code and I want to make sure that they don't mess things up.

我很高兴能停下来例如,他们使用反射来故意破坏东西,但是如果他们这样做,我希望它是因为他们是故意这样做的,而不仅仅是粗心大意。

I appreciate that there I can't stop them from deliberately breaking stuff, for example, using reflection, but if they do this I want it to be because they are doing it on purpose rather than just being careless.

事后思考

我想我可以将事件附加到 IsTypeDefault 属性,并让集合类订阅该事件,让它(集合)在允许之前进行验证(或不是)对集合中实例的更改。是吗?

I suppose I could attach an event to the IsTypeDefault property and have the collection class subscribe to the event, have it (the collection) do the verification before allowing (or not) the change to the instance in the collection. Yes?

推荐答案

如果 MyCollection MyClass 在同一程序集中,但使用它的开发人员不在同一组件中-那么这是使setter internal

If both MyCollection and MyClass are within the same assembly, but the developers using it are not - then its a simple case of making the setter internal

public abstract class MyClass
{
    // other properties
    public bool IsTypeDefault {get; internal set;}
}

这篇关于在集合中的对象上设置属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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