как иметь пользовательский атрибут в ConfigurationElementCollection?

В Java все переменные, которые вы объявляете, на самом деле являются «ссылками» на объекты (или примитивы), а не самими объектами.

При попытке выполнить один метод объекта , ссылка просит живой объект выполнить этот метод. Но если ссылка ссылается на NULL (ничего, нуль, void, nada), то нет способа, которым метод будет выполнен. Тогда runtime сообщит вам об этом, выбросив исключение NullPointerException.

Ваша ссылка «указывает» на нуль, таким образом, «Null -> Pointer».

Объект живет в памяти виртуальной машины пространство и единственный способ доступа к нему - использовать ссылки this. Возьмем этот пример:

public class Some {
    private int id;
    public int getId(){
        return this.id;
    }
    public setId( int newId ) {
        this.id = newId;
    }
}

И в другом месте вашего кода:

Some reference = new Some();    // Point to a new object of type Some()
Some otherReference = null;     // Initiallly this points to NULL

reference.setId( 1 );           // Execute setId method, now private var id is 1

System.out.println( reference.getId() ); // Prints 1 to the console

otherReference = reference      // Now they both point to the only object.

reference = null;               // "reference" now point to null.

// But "otherReference" still point to the "real" object so this print 1 too...
System.out.println( otherReference.getId() );

// Guess what will happen
System.out.println( reference.getId() ); // :S Throws NullPointerException because "reference" is pointing to NULL remember...

Это важно знать - когда больше нет ссылок на объект (в пример выше, когда reference и otherReference оба указывают на null), тогда объект «недоступен». Мы не можем работать с ним, поэтому этот объект готов к сбору мусора, и в какой-то момент VM освободит память, используемую этим объектом, и выделит другую.

25
задан jojo 12 January 2012 в 02:32
поделиться

4 ответа

Предположим, у вас есть этот файл .config:

<configuration>
    <configSections>
        <section name="mySection" type="ConsoleApplication1.MySection, ConsoleApplication1" /> // update type  & assembly names accordingly
    </configSections>

    <mySection>
        <MyCollection default="one">
            <entry name="one" />
            <entry name="two" />
        </MyCollection>
    </mySection>
</configuration>

Затем с помощью этого кода:

public class MySection : ConfigurationSection
{
    [ConfigurationProperty("MyCollection", Options = ConfigurationPropertyOptions.IsRequired)]
    public MyCollection MyCollection
    {
        get
        {
            return (MyCollection)this["MyCollection"];
        }
    }
}

[ConfigurationCollection(typeof(EntryElement), AddItemName = "entry", CollectionType = ConfigurationElementCollectionType.BasicMap)]
public class MyCollection : ConfigurationElementCollection
{
    protected override ConfigurationElement CreateNewElement()
    {
        return new EntryElement();
    }

    protected override object GetElementKey(ConfigurationElement element)
    {
        if (element == null)
            throw new ArgumentNullException("element");

        return ((EntryElement)element).Name;
    }

    [ConfigurationProperty("default", IsRequired = false)]
    public string Default
    {
        get
        {
            return (string)base["default"];
        }
    }
}

public class EntryElement : ConfigurationElement
{
    [ConfigurationProperty("name", IsRequired = true, IsKey = true)]
    public string Name
    {
        get
        {
            return (string)base["name"];
        }
    }
}

вы можете прочитать конфигурацию с атрибутом «default», например так: :

    MySection section = (MySection)ConfigurationManager.GetSection("mySection");
    Console.WriteLine(section.MyCollection.Default);

Это выведет «один»

54
ответ дан Simon Mourier 12 January 2012 в 02:32
поделиться

Я не знаю, возможно ли иметь значение по умолчанию в ConfigurationElementCollection. (у него не было свойства для значения по умолчанию).

Я полагаю, вы должны реализовать это самостоятельно. Посмотрите на пример ниже.

public class Repository : ConfigurationElement
{
    [ConfigurationProperty("key", IsRequired = true)]
    public string Key
    {
        get { return (string)this["key"]; }
    }

    [ConfigurationProperty("value", IsRequired = true)]
    public string Value
    {
        get { return (string)this["value"]; }
    }
}

public class RepositoryCollection : ConfigurationElementCollection
{
    protected override ConfigurationElement CreateNewElement()
    {
        return new Repository();
    }

    protected override object GetElementKey(ConfigurationElement element)
    {
        return (element as Repository).Key;
    }

    public Repository this[int index]
    {
        get { return base.BaseGet(index) as Repository; }
    }

    public new Repository this[string key]
    {
        get { return base.BaseGet(key) as Repository; }
    }

}

public class MyConfig : ConfigurationSection
{
    [ConfigurationProperty("currentRepository", IsRequired = true)]
    private string InternalCurrentRepository
    {
        get { return (string)this["currentRepository"]; }
    }

    [ConfigurationProperty("repositories", IsRequired = true)]
    private RepositoryCollection InternalRepositories
    {
        get { return this["repositories"] as RepositoryCollection; }
    }
}

Вот XML-конфигурация:

  <myConfig currentRepository="SQL2008">
    <repositories>
      <add key="SQL2008" value="abc"/>
      <add key="Oracle" value="xyz"/>
    </repositories>
  </myConfig>

И затем, используя свой код, вы получаете доступ к элементу по умолчанию, используя следующее:

MyConfig conf = (MyConfig)ConfigurationManager.GetSection("myConfig");
string myValue = conf.Repositories[conf.CurrentRepository].Value;

Конечно, MyConfig Класс может скрыть детали доступа к свойствам Repositories и CurrentRepository. У вас может быть свойство DefaultRepository (типа Repository) в классе MyConfig, чтобы вернуть это.

5
ответ дан Fabio 12 January 2012 в 02:32
поделиться

Это может быть немного поздно, но может быть полезно для других.

Это возможно, но с некоторой модификацией.

  • ConfigurationElementCollection наследует ConfigurationElement, так как «this [string]» доступна в ConfigurationElement.

  • Обычно, когда ConfigurationElementCollection наследуется и реализуется в другом классе, «this [string]» скрывается с «new this [string]».

  • Один из способов обойти это - создать другую реализацию этого [], такую ​​как «this [string, string]»

пример ниже.

public class CustomCollection : ConfigurationElementCollection
{
    protected override ConfigurationElement CreateNewElement()
    {
        return new CustomElement();
    }

    protected override object GetElementKey(ConfigurationElement element)
    {
        return ((CustomElement)element).Name;
    }

    public CustomElement this[int index]
    {
        get { return (CustomElement)base.BaseGet(index); }
        set
        {
            if (BaseGet(index) != null)
                BaseRemoveAt(index);

            BaseAdd(index, value);
        }
    }

    // ConfigurationElement this[string] now becomes hidden in child class
    public new CustomElement this[string name]
    {
        get { return (CustomElement)BaseGet(name); }
    }

    // ConfigurationElement this[string] is now exposed
    // however, a value must be entered in second argument for property to be access
    // otherwise "this[string]" will be called and a CustomElement returned instead
    public object this[string name, string str = null]
    {
        get { return base[name]; }
        set { base[name] = value; }
    }
}
1
ответ дан clattaclism 12 January 2012 в 02:32
поделиться

Если вы хотите обобщить его, это должно помочь:

using System.Configuration;

namespace Abcd
{
  // Generic implementation of ConfigurationElementCollection.
  [ConfigurationCollection(typeof(ConfigurationElement))]
  public class ConfigurationElementCollection<T> : ConfigurationElementCollection
                                         where T : ConfigurationElement, IConfigurationElement, new()
  {
    protected override ConfigurationElement CreateNewElement()
    {
      return new T();
    }

    protected override object GetElementKey(ConfigurationElement element)
    {
      return ((IConfigurationElement)element).GetElementKey();
    }

    public T this[int index]
    {
      get { return (T)BaseGet(index); }
    }

    public T GetElement(object key)
    {
      return (T)BaseGet(key);
    }
  }
}

Вот интерфейс, указанный выше:

namespace Abcd
{
  public interface IConfigurationElement
  {
    object GetElementKey();
  }
}
0
ответ дан GaTechThomas 12 January 2012 в 02:32
поделиться
Другие вопросы по тегам:

Похожие вопросы: