Twitter iPhone pliant OnePlus 11 PS5 Disney+ Orange Livebox Windows 11

serialization d'une propriété de type List

8 réponses
Avatar
Magalie
Bonjour a tous,

J'ai creer une propriété de type List<string>, lorsque je veut la modifier
en mode design, une fenetre s'ouvre ou je peut rentrer les element de ma
liste (j'ai dut creer un editeur pour que ca marche) mais le probleme est
que quand je sors de cette fenetre les donnees ne sont pas serializer.
j'aimerais pouvoir les serializer sous forme de string dans les attributs
(je pense que je doit utiliser un typeConverter) mais je n'y arrive pas.

pourriez vous m'aider s'il vous plait il ne me reste qu'une semaine pour
terminer.

Magalie

8 réponses

Avatar
Ambassadeur Kosh
que se passe t'il si tu ajoutes l'attribut [Serializable()] ?
Avatar
Magalie
merci, mais il ne serialize toujours pas, voici mon code que j'ai creer dans
un nouveau projet pour mes tests :
dans le doute de savoir ou je devait le rajouter je l'ai mis sur toutes les
class mais ca ne change rien.
comme au depart il ne rajoute que : TestList-Capacity="4" ... :-(

class du composant que je rajoute dans lequel j'ai ma propriete :

[DefaultProperty("Text")]

[ToolboxData("<{0}:Test runat=server></{0}:Test>")]

[Serializable()]

public class Test : WebControl

{

private string text;



[Bindable(true)]

[Category("Appearance")]

[DefaultValue("")]

public string Text

{

get { return text; }

set { text = value; }

}





private List<string> testList = new List<string>();



[Bindable(true)]

[Category("Test")]

[DefaultValue("")]

[TypeConverter(typeof(ConverterTest))]

[PersistenceMode(PersistenceMode.Attribute)]

[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]

[Editor(typeof(editeur),typeof(System.Drawing.Design.UITypeEditor))]

public List<string> TestList

{

get

{

if (testList == null)

return new List<string>();

return testList;

}

set { testList = value; }

}



protected override void Render(HtmlTextWriter output)

{

output.Write(Text);

}

}



class qui defini l'editeur :



[Serializable()]

class editeur : CollectionEditor

{

public editeur()

: base (typeof(List<string>))

{

}

protected override object CreateInstance(Type itemType)

{

return "";

}

protected override Type CreateCollectionItemType()

{

return typeof(string);

}



}



class qui defini le converter :



[Serializable()]

public class ConverterTest : TypeConverter

{

public override bool CanConvertTo(ITypeDescriptorContext context,
Type destinationType)

{

//if (destinationType == typeof(List<string>))

// return true;

//

//bool b = base.CanConvertTo(context, destinationType);

//return b;

return true;

}

public override object ConvertTo(ITypeDescriptorContext context,
System.Globalization.CultureInfo culture, object value, Type
destinationType)

{

if (destinationType == typeof(string))

{

List<string> list = (List<string>)value;

string s = "lol";

for (int i = 0; i < list.Count; i++)

s += list[i].ToString() + ((i + 1 < list.Count) ? "-" :
"");



context.PropertyDescriptor.SetValue(context.Instance, s);

return s;

}

else if (destinationType ==
typeof(System.ComponentModel.Design.Serialization.InstanceDescriptor))

{

System.Reflection.ConstructorInfo ci =
typeof(List<string>).GetConstructor(new Type[0]);

return new
System.ComponentModel.Design.Serialization.InstanceDescriptor(ci, null);

}

return "bof...";

}

public override bool CanConvertFrom(ITypeDescriptorContext context,
Type sourceType)

{

System.Windows.Forms.MessageBox.Show("CanConvertFrom: " +
sourceType.ToString());

if (sourceType == typeof(string))

{

return true;

}

return base.CanConvertFrom(context, sourceType);



}

public override object ConvertFrom(ITypeDescriptorContext context,
System.Globalization.CultureInfo culture, object value)

{

System.Windows.Forms.MessageBox.Show("ConvertFrom: " +
value.GetType().ToString());



if (value is string)

{

System.Windows.Forms.MessageBox.Show(value.ToString());

string[] v = ((string)value).Split(new char[] { '-' },
StringSplitOptions.None);

return new List<string>(v);

}

return base.ConvertFrom(context, culture, value);

}




"Ambassadeur Kosh" a écrit dans le message de
news:
que se passe t'il si tu ajoutes l'attribut [Serializable()] ?



Avatar
Ambassadeur Kosh
voici le code d'une liste qui fonctionn(ait) avec le designer.
il date d'il y'a 3 mois et je ne l'ai pas retesté depuis...


/// <summary>
/// List avec Event sur modification du contenu
/// </summary>
/// <typeparam name="T">type des elements manipulés dans la
liste</typeparam>
/// <remarks>
/// ne fonctionne pas avec le Designer pour le moment.
/// </remarks>
public class EnhancedList<T> : IList<T>
{
public EnhancedList(IList<T> list)
{
this._list = list;
}

private IList<T> _list;

#region Events

public event CollectionChangedHandler<T> CollectionChanged;

#endregion

#region IList<T> Members

/// <summary>
/// Searches for the specified object and returns the zero-based index of
the first occurrence within the entire List
/// </summary>
/// <param name="item">The object to locate in the List. The value can be
null for reference types</param>
/// <returns>The zero-based index of the first occurrence of item within
the entire, if found; otherwise, -1</returns>
public int IndexOf(T item)
{
return _list.IndexOf(item);
}
/// <summary>
/// Inserts an element into the at the specified index.
/// </summary>
/// <param name="index">The zero-based index at which item should be
inserted.</param>
/// <param name="item">The object to insert. The value can be null for
reference types.</param>
public void Insert(int index, T item)
{
_list.Insert(index, item);

if (CollectionChanged != null)
CollectionChanged(CollectionChangeAction.Add, item);
}
/// <summary>
/// Removes the element at the specified index of the List.
/// </summary>
/// <param name="index">The zero-based index of the element to
remove.</param>
public void RemoveAt(int index)
{
T item = _list[index];

_list.RemoveAt(index);

if (CollectionChanged != null)
CollectionChanged(CollectionChangeAction.Remove, item);
}
/// <summary>
/// Gets or sets the element at the specified index.
/// </summary>
/// <param name="index">The zero-based index of the element to get or
set.</param>
/// <returns>The element at the specified index.</returns>
public T this[int index]
{
get
{
return _list[index];
}
set
{
_list[index] = value;

if (CollectionChanged != null)
CollectionChanged(CollectionChangeAction.Refresh, value);
}
}

#endregion

#region ICollection<T> Members

/// <summary>
/// Adds an object to the end of the List.
/// </summary>
/// <param name="item">The object to be added to the end of the . The
value can be null for reference types.</param>
public void Add(T item)
{
_list.Add(item);

if (CollectionChanged != null)
CollectionChanged(CollectionChangeAction.Add, item);
}
/// <summary>
/// Removes all elements from the List.
/// </summary>
public void Clear()
{
if (CollectionChanged != null)
foreach (T item in _list)
CollectionChanged(CollectionChangeAction.Remove, item);

_list.Clear();
}
/// <summary>
/// Determines whether an element is in the List.
/// </summary>
/// <param name="item">The object to locate in the . The value can be null
for reference types.</param>
/// <returns>true if item is found in the ; otherwise, false.</returns>
public bool Contains(T item)
{
return _list.Contains(item);
}
/// <summary>
/// Copies the entire to a compatible one-dimensional , starting at the
specified index of the target array.
/// </summary>
/// <param name="array">The one-dimensional that is the destination of the
elements copied from . The must have zero-based indexing.</param>
/// <param name="arrayIndex">The zero-based index in array at which
copying begins.</param>
public void CopyTo(T[] array, int arrayIndex)
{
_list.CopyTo(array, arrayIndex);
}
/// <summary>
/// The number of elements actually contained in the List.
/// </summary>
/// <value>
/// Gets the number of elements actually contained in the List.
/// </value>
public int Count
{
get { return _list.Count; }
}
/// <summary>
/// When implemented by a class, gets a value indicating whether the IList
is read-only.
/// </summary>
/// <value>
/// true if the IList is read-only; otherwise, false.
/// </value>
/// <remarks>
/// A collection that is read-only does not allow the addition, removal,
or modification of elements after the collection is created.
/// A collection that is read-only is simply a collection with a wrapper
that prevents modifying the collection; therefore, if changes are made to
the underlying collection, the read-only collection reflects those changes.
/// </remarks>
public bool IsReadOnly
{
get { return _list.IsReadOnly; }
}
/// <summary>
/// Removes the first occurrence of a specific object from the List.
/// </summary>
/// <param name="item">The object to remove from the List. The value can
be null for reference types.</param>
/// <returns>true if item is successfully removed; otherwise, false. This
method also returns false if item was not found in the original
List.</returns>
public bool Remove(T item)
{
bool removed = _list.Remove(item);

if (removed)
if (CollectionChanged != null)
CollectionChanged(CollectionChangeAction.Remove, item);

return removed;
}

#endregion

#region IEnumerable<T> Members

/// <summary>
/// Returns an enumerator that iterates through the List.
/// </summary>
/// <returns>An IEnumerator for the List.</returns>
public IEnumerator<T> GetEnumerator()
{
return _list.GetEnumerator();
}

#endregion

#region IEnumerable Members

/// <summary>
/// Returns an enumerator that iterates through the List.
/// </summary>
/// <returns>An IEnumerator for the List.</returns>
System.Collections.IEnumerator
System.Collections.IEnumerable.GetEnumerator()
{
return _list.GetEnumerator();
}

#endregion
}
Avatar
Magalie
merci je vais essayer. tu ne la pas fait de la même manière que moi, je ne
chercher peut etre po au bon endroit merci


"Ambassadeur Kosh" a écrit dans le message de
news: u%23u3tt%
voici le code d'une liste qui fonctionn(ait) avec le designer.
il date d'il y'a 3 mois et je ne l'ai pas retesté depuis...


/// <summary>
/// List avec Event sur modification du contenu
/// </summary>
/// <typeparam name="T">type des elements manipulés dans la
liste</typeparam>
/// <remarks>
/// ne fonctionne pas avec le Designer pour le moment.
/// </remarks>
public class EnhancedList<T> : IList<T>
{
public EnhancedList(IList<T> list)
{
this._list = list;
}

private IList<T> _list;

#region Events

public event CollectionChangedHandler<T> CollectionChanged;

#endregion

#region IList<T> Members

/// <summary>
/// Searches for the specified object and returns the zero-based index of
the first occurrence within the entire List
/// </summary>
/// <param name="item">The object to locate in the List. The value can be
null for reference types</param>
/// <returns>The zero-based index of the first occurrence of item within
the entire, if found; otherwise, -1</returns>
public int IndexOf(T item)
{
return _list.IndexOf(item);
}
/// <summary>
/// Inserts an element into the at the specified index.
/// </summary>
/// <param name="index">The zero-based index at which item should be
inserted.</param>
/// <param name="item">The object to insert. The value can be null for
reference types.</param>
public void Insert(int index, T item)
{
_list.Insert(index, item);

if (CollectionChanged != null)
CollectionChanged(CollectionChangeAction.Add, item);
}
/// <summary>
/// Removes the element at the specified index of the List.
/// </summary>
/// <param name="index">The zero-based index of the element to
remove.</param>
public void RemoveAt(int index)
{
T item = _list[index];

_list.RemoveAt(index);

if (CollectionChanged != null)
CollectionChanged(CollectionChangeAction.Remove, item);
}
/// <summary>
/// Gets or sets the element at the specified index.
/// </summary>
/// <param name="index">The zero-based index of the element to get or
set.</param>
/// <returns>The element at the specified index.</returns>
public T this[int index]
{
get
{
return _list[index];
}
set
{
_list[index] = value;

if (CollectionChanged != null)
CollectionChanged(CollectionChangeAction.Refresh, value);
}
}

#endregion

#region ICollection<T> Members

/// <summary>
/// Adds an object to the end of the List.
/// </summary>
/// <param name="item">The object to be added to the end of the . The
value can be null for reference types.</param>
public void Add(T item)
{
_list.Add(item);

if (CollectionChanged != null)
CollectionChanged(CollectionChangeAction.Add, item);
}
/// <summary>
/// Removes all elements from the List.
/// </summary>
public void Clear()
{
if (CollectionChanged != null)
foreach (T item in _list)
CollectionChanged(CollectionChangeAction.Remove, item);

_list.Clear();
}
/// <summary>
/// Determines whether an element is in the List.
/// </summary>
/// <param name="item">The object to locate in the . The value can be
null for reference types.</param>
/// <returns>true if item is found in the ; otherwise, false.</returns>
public bool Contains(T item)
{
return _list.Contains(item);
}
/// <summary>
/// Copies the entire to a compatible one-dimensional , starting at the
specified index of the target array.
/// </summary>
/// <param name="array">The one-dimensional that is the destination of
the elements copied from . The must have zero-based indexing.</param>
/// <param name="arrayIndex">The zero-based index in array at which
copying begins.</param>
public void CopyTo(T[] array, int arrayIndex)
{
_list.CopyTo(array, arrayIndex);
}
/// <summary>
/// The number of elements actually contained in the List.
/// </summary>
/// <value>
/// Gets the number of elements actually contained in the List.
/// </value>
public int Count
{
get { return _list.Count; }
}
/// <summary>
/// When implemented by a class, gets a value indicating whether the
IList is read-only.
/// </summary>
/// <value>
/// true if the IList is read-only; otherwise, false.
/// </value>
/// <remarks>
/// A collection that is read-only does not allow the addition, removal,
or modification of elements after the collection is created.
/// A collection that is read-only is simply a collection with a wrapper
that prevents modifying the collection; therefore, if changes are made to
the underlying collection, the read-only collection reflects those
changes.
/// </remarks>
public bool IsReadOnly
{
get { return _list.IsReadOnly; }
}
/// <summary>
/// Removes the first occurrence of a specific object from the List.
/// </summary>
/// <param name="item">The object to remove from the List. The value can
be null for reference types.</param>
/// <returns>true if item is successfully removed; otherwise, false. This
method also returns false if item was not found in the original
List.</returns>
public bool Remove(T item)
{
bool removed = _list.Remove(item);

if (removed)
if (CollectionChanged != null)
CollectionChanged(CollectionChangeAction.Remove, item);

return removed;
}

#endregion

#region IEnumerable<T> Members

/// <summary>
/// Returns an enumerator that iterates through the List.
/// </summary>
/// <returns>An IEnumerator for the List.</returns>
public IEnumerator<T> GetEnumerator()
{
return _list.GetEnumerator();
}

#endregion

#region IEnumerable Members

/// <summary>
/// Returns an enumerator that iterates through the List.
/// </summary>
/// <returns>An IEnumerator for the List.</returns>
System.Collections.IEnumerator
System.Collections.IEnumerable.GetEnumerator()
{
return _list.GetEnumerator();
}

#endregion
}




Avatar
Ambassadeur Kosh
> merci je vais essayer. tu ne la pas fait de la même manière que moi, je ne
chercher peut etre po au bon endroit merci



j'ai remis la main sur les TypeConverter, mais c'est superlourdingue.
si ça ne marche pas, je te post un exemple de code
Avatar
Magalie
salut bon apres une apres midi dessus et un debut de matinée, je n'arrive
pas a le faire marché sur mon projet. je veux bien l'exemple de code (tant
pis si c'est lourd) merci.

"Ambassadeur Kosh" a écrit dans le message de
news: uWmKf$%
merci je vais essayer. tu ne la pas fait de la même manière que moi, je
ne chercher peut etre po au bon endroit merci



j'ai remis la main sur les TypeConverter, mais c'est superlourdingue.
si ça ne marche pas, je te post un exemple de code



Avatar
Ambassadeur Kosh
http://www.vcstimeless.fr/dotnettips/ow.asp?SerializePropertyCollection

merci à Benoist Demeurre de VcsTimeless pour ce excellent site
Avatar
Magalie
merci


"Ambassadeur Kosh" a écrit dans le message de
news: OfnH$
http://www.vcstimeless.fr/dotnettips/ow.asp?SerializePropertyCollection

merci à Benoist Demeurre de VcsTimeless pour ce excellent site