Коллекции в .NET Framework Class Library
Есть логика намерений и логика обстоятельств,
последняя всегда сильнее .
Re: Коллекции в .NET Framework Class Library
От:
Аноним
Дата: 30.01.04 15:46
Оценка:
Hi Vlad, I attached source file, could suggest how to fix that problem, please ?
Thx, Dmitry MS
Сценарий:
Создается коллекция объектов типа А (тип А имеет вложенную коллекцию типов B). В конструктор типа А передается коллекция типов B, предопределяя стартовый набор типов B в каждом из объектов А (наследовать смысла нет — слишком раznije объекты). После добавления А в коллекцию над екземпляром А проводятся изменения (вызывается процедура Do, принимающая параметером А). Ета процедура меняет не только А, но также все уже имеущиеся в коллекции ехемпляри А, как будто бы ето к ним относится.
Есть идея, что это поведение обусловлено фактом передачи в конструктор А мастер коллекции, которая всегда передается по ссилке (disregard of ByVal or ByRef). Таким образом, все созданние екземпляры А имеют не независимие коллекции типов B, а ссылку на одну такую коллекцию, заданную при их создании.
Вопрос:
Как ограничить область применения преобразований над А — конкретним екземпляром, передаваемым в процедуру Ду.
Спасибо.
P.S. Source.
namespace Refs
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Button button1;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null ;
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if ( disposing )
{
if (components != null )
{
components.Dispose();
}
}
base .Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this .button1 = new System.Windows.Forms.Button();
this .SuspendLayout();
//
// button1
//
this .button1.Location = new System.Drawing.Point(232, 128);
this .button1.Name = "button1" ;
this .button1.TabIndex = 0;
this .button1.Text = "button1" ;
this .button1.Click += new System.EventHandler(this .button1_Click);
//
// Form1
//
this .AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this .ClientSize = new System.Drawing.Size(688, 365);
this .Controls.Add(this .button1);
this .Name = "Form1" ;
this .Text = "Form1" ;
this .ResumeLayout(false );
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void button1_Click(object sender, System.EventArgs e)
{
Master m = new Master();
m.PredefinedFieldSet.Add(new Field("MyPredefinedField" ));
Detail d;
//adds 10 detial items into master
for (int i =0; i < 10; i++) {
d = new Detail(m.PredefinedFieldSet);
m.Details.Add(d);
}
//assign values to detail items (expected from 1 to 10)
m.AssignValues();
foreach (Detail d2 in m.Details) {
MessageBox.Show(d2.DerivedSet[0].Value.ToString());
}
}
}
//classes
//Field
public class Field
{
private int _someValue;
private string _name;
public Field(string Name)
{
_name = Name;
}
public int Value
{
get
{
return _someValue;
}
set
{
_someValue = value ;
}
}
public string Name
{
get
{
return _name;
}
set
{
_name = value ;
}
}
}
//Fields collection
public class FieldsCollection: CollectionBase
{
public int Add(Field Item)
{
return this .List.Add(Item);
}
public Field this [int Index]
{
get
{
return (Field) this .List[Index];
}
}
}
//Master object
public class Master
{
private FieldsCollection _predefinedSet = new FieldsCollection();
private DetailsCollection _detials = new DetailsCollection();
int i;
public FieldsCollection PredefinedFieldSet
{
get
{
return _predefinedSet;
}
}
public DetailsCollection Details
{
get
{
return _detials;
}
}
//problem
public void AssignValues() {
foreach (Detail d in this .Details) {
i = i + 1;
d.DerivedSet[0].Value = i;
}
}
}
//Detial object
public class Detail
{
private FieldsCollection _derivedSet = new FieldsCollection();
public Detail(FieldsCollection DerivedSet)
{
_derivedSet = DerivedSet;
}
public FieldsCollection DerivedSet
{
get
{
return _derivedSet;
}
}
}
//Details collection
public class DetailsCollection: CollectionBase
{
public int Add(Detail Item)
{
return this .List.Add(Item);
}
public Detail this [int Index]
{
get
{
return (Detail) this .List[Index];
}
}
}
}
Re[2]: Коллекции в .NET Framework Class Library
Здравствуйте, <Аноним>, Вы писали:
А>Вопрос:
А>Как ограничить область применения преобразований над А — конкретним екземпляром, передаваемым в процедуру Ду.
Незнаю насколько верно я понял вопрос. Может быть тут проблема в организации коллекций, а не в огранизчении?
... << RSDN@Home 1.1.3 beta 2 >>
Есть логика намерений и логика обстоятельств,
последняя всегда сильнее .
Re[3]: Коллекции в .NET Framework Class Library
I can't prevent class, derived from CollectionBase from being passed ByRef... That's my problem. I though of ref/out, but it doesn't seem be to be useful in my case.
Eventually I've got it sorted by the way... The lesson I've learnt from that is you can't reuse literally ANYTHING except of primitve values from existing colleciton, unless you want your collection to share address space with it's orginator (with all consiquent problems)...
I've tryed to create new collection and re-populate it with items of existing one (thought it'll separate them) — not gonna work... By times it looked like a feaver...
The solution was to use primitve proveprites of each item and reacreate item themselvs, rather than set them as as children for brand new collection.
Not too elegant but works.
Cheers.
Re[4]: Коллекции в .NET Framework Class Library
apologies for the crappy English.
Re: Коллекции в .NET Framework Class Library
От:
AsIs
Дата: 30.01.04 17:17
Оценка:
Здравствуйте, Чистяков Владислав (VladD2), Вы писали:
ЧВV>Статья:
ЧВV>Авторы:
ЧВV> Чистяков Владислав (VladD2)
ЧВV>Аннотация:
ЧВV>Рассказ о коллекциях в .NET Framework. Статья будет полезна как начинающим программистам, так и желающим более подробно изучить этот вопрос.
в новом framwork появится IList, IDictionary коллекция. Ну там доспуп (вставка, чтение, замена и удаление) будет по позиции как в IList и доступ по ключу как в IDictionary... послухам эта коллекция использоватся где в WEB гуе будет. не знаю как называется,
вот кодогенератор типизированной коллекции для любого фреймоврка
пример консольного вызова
generate.exe /Key:Guid /Item:String /Dictionary:My.Collections.StringListKeyedByGuid
using System;
using System.Xml;
using System.IO;
using System.Text;
using System.Data;
using System.Collections;
using System.Runtime.Serialization;
using System.Xml.Serialization;
namespace CodeGen
{
public class MainClass
{
public static string TargetSource;
public static string DefaultTargetSource { get { FileInfo fi=new FileInfo(TemplateSource); return fi.Directory.FullName+"\\AutoGeneratedBy" +fi.Name+".unknown" ; } }
public static string TemplateSource=@"Template.OrderedDictionary.aspx" ;
static StringWriter newConsole;
public static void SwitchOutputToFile(string fileName)
{
DumpOutput();
newConsole=new StringWriter();
Console.SetOut(newConsole);
TargetSource=fileName;
}
static void DumpOutput()
{
FileInfo fi=new FileInfo(TargetSource);
try { Directory.CreateDirectory(fi.Directory.FullName); } catch {}
using (FileStream outStream=new FileStream(TargetSource, FileMode.Create, FileAccess.Write, FileShare.Read))
{
using (StreamWriter writer=new StreamWriter(outStream, Encoding.Default))
{
writer.WriteLine(newConsole.ToString());
}
}
}
public static void Main()
{
TargetSource=DefaultTargetSource;
TextWriter console=Console.Out;
newConsole=new StringWriter();
Console.SetOut(newConsole);
OrderedDictionaryRules rules=new OrderedDictionaryRules();
{ Console.Write("\x000D\x000A" ); }
TargetSource=rules.TargetSource;
{ Console.Write("\x000D\x000A\x000D\x000Ausing System;\x000D\x000Ausing System.Collectio" ); }
{ Console.Write("ns;\x000D\x000A\x000D\x000A" ); }
Console.Write(rules.Namespace.Length>0 ? string .Format("namespace {0}\n{{" , rules.Namespace) : "" );
{ Console.Write("\x000D\x000A /******************************************************" ); }
{ Console.Write("*******************\x000D\x000A /* Ordered (IList) Dictionary (IDic" ); }
{ Console.Write("tionary) " ); }
Console.Write(rules.EntryClass);
{ Console.Write("\x000D\x000A /* critical perfomance operations: \x000D\x000A /* " ); }
{ Console.Write(" + Add(), IList.Add(), IDictionary.Add();\x000D\x000A /* + fore" ); }
{ Console.Write("ach enumerating; \x000D\x000A /* + " ); }
Console.Write(rules.ItemClass);
{ Console.Write(" this[int index] { get; set; }\x000D\x000A /* + " ); }
Console.Write(rules.ItemClass);
{ Console.Write(" this[" ); }
Console.Write(rules.KeyClass);
{ Console.Write(" key] { get; set; }\x000D\x000A /* CAUTION: any other operation per" ); }
{ Console.Write("fomance accidental\x000D\x000A /************************************" ); }
{ Console.Write("*************************************/\x000D\x000A [Serializable]\x000D" ); }
{ Console.Write("\x000A public class " ); }
Console.Write(rules.EntryClass);
{ Console.Write("\x000D\x000A {\x000D\x000A public " ); }
Console.Write(rules.EntryClass);
{ Console.Write("(" ); }
Console.Write(rules.KeyClass);
{ Console.Write(" key, " ); }
Console.Write(rules.ItemClass);
{ Console.Write(" value)\x000D\x000A {\x000D\x000A this._Key=key;\x000D\x000A" ); }
{ Console.Write(" this._Value=value;\x000D\x000A }\x000D\x000A public " ); }
Console.Write(rules.KeyClass);
{ Console.Write(" Key\x000D\x000A {\x000D\x000A get { return _Key; } \x000D\x000A" ); }
{ Console.Write(" set { _Key=value; }\x000D\x000A }\x000D\x000A public " ); }
Console.Write(rules.ItemClass);
{ Console.Write(" Value\x000D\x000A {\x000D\x000A get { return _Value; } \x000D" ); }
{ Console.Write("\x000A set { _Value=value; }\x000D\x000A }\x000D\x000A " ); }
{ Console.Write(" private " ); }
Console.Write(rules.KeyClass);
{ Console.Write(" _Key;\x000D\x000A private " ); }
Console.Write(rules.ItemClass);
{ Console.Write(" _Value;\x000D\x000A }\x000D\x000A \x000D\x000A [Serializable]" ); }
{ Console.Write("\x000D\x000A public class " ); }
Console.Write(rules.Class);
{ Console.Write(" : IDictionary, IList\x000D\x000A {\x000D\x000A private Hasht" ); }
{ Console.Write("able objectTable = new Hashtable ();\x000D\x000A private ArrayLi" ); }
{ Console.Write("st objectList = new ArrayList ();\x000D\x000A\x000D\x000A public" ); }
{ Console.Write(" void Add (" ); }
Console.Write(rules.KeyClass);
{ Console.Write(" key, " ); }
Console.Write(rules.ItemClass);
{ Console.Write(" value)\x000D\x000A {\x000D\x000A objectTable.Add (ke" ); }
{ Console.Write("y, value);\x000D\x000A objectList.Add (new DictionaryEntry (" ); }
{ Console.Write("key, value));\x000D\x000A }\x000D\x000A\x000D\x000A publi" ); }
{ Console.Write("c void Clear ()\x000D\x000A {\x000D\x000A objectTable" ); }
{ Console.Write(".Clear ();\x000D\x000A objectList.Clear ();\x000D\x000A " ); }
{ Console.Write(" }\x000D\x000A\x000D\x000A public bool Contains (" ); }
Console.Write(rules.KeyClass);
{ Console.Write(" key)\x000D\x000A {\x000D\x000A return objectTable.Co" ); }
{ Console.Write("ntains (key);\x000D\x000A }\x000D\x000A\x000D\x000A #regi" ); }
{ Console.Write("on IDictionary Implementation\x000D\x000A bool IDictionary.Conta" ); }
{ Console.Write("ins (object key)\x000D\x000A {\x000D\x000A " ); }
Console.Write(rules.ValidateKeyIsNull("key" , "IDictionary.Contains()" ));
{ Console.Write("\x000D\x000A " ); }
Console.Write(rules.ValidateKeyType("key" , "IDictionary.Contains()" ));
{ Console.Write("\x000D\x000A return Contains ((" ); }
Console.Write(rules.KeyClass);
{ Console.Write(")key);\x000D\x000A }\x000D\x000A \x000D\x000A void" ); }
{ Console.Write(" IDictionary.Add (object key, object value)\x000D\x000A {\x000D\x000A" ); }
{ Console.Write(" " ); }
Console.Write(rules.ValidateKeyIsNull("key" , "IDictionary.Add()" ));
{ Console.Write("\x000D\x000A " ); }
Console.Write(rules.ValidateKeyType("key" , "IDictionary.Add()" ));
{ Console.Write("\x000D\x000A " ); }
Console.Write(rules.ValidateItemType("value" , "IDictionary.Add()" ));
{ Console.Write("\x000D\x000A Add ((" ); }
Console.Write(rules.KeyClass);
{ Console.Write(")key, (" ); }
Console.Write(rules.ItemClass);
{ Console.Write(")value);\x000D\x000A }\x000D\x000A\x000D\x000A void IDict" ); }
{ Console.Write("ionary.Remove (object key)\x000D\x000A {\x000D\x000A " ); }
Console.Write(rules.ValidateKeyIsNull("key" , "IDictionary.Remove()" ));
{ Console.Write("\x000D\x000A " ); }
Console.Write(rules.ValidateKeyType("key" , "IDictionary.Remove()" ));
{ Console.Write("\x000D\x000A Remove((" ); }
Console.Write(rules.KeyClass);
{ Console.Write(")key);\x000D\x000A }\x000D\x000A\x000D\x000A object IDict" ); }
{ Console.Write("ionary.this[object key]\x000D\x000A {\x000D\x000A get\x000D" ); }
{ Console.Write("\x000A {\x000D\x000A " ); }
Console.Write(rules.ValidateKeyIsNull("key" , "IDictionary.Get[key]" ));
{ Console.Write("\x000D\x000A " ); }
Console.Write(rules.ValidateKeyType("key" , "IDictionary.Get[key]" ));
{ Console.Write("\x000D\x000A return this[(" ); }
Console.Write(rules.KeyClass);
{ Console.Write(")key];\x000D\x000A }\x000D\x000A set \x000D\x000A " ); }
{ Console.Write(" {\x000D\x000A " ); }
Console.Write(rules.ValidateKeyIsNull("key" , "IDictionary.Set[key]" ));
{ Console.Write("\x000D\x000A " ); }
Console.Write(rules.ValidateKeyType("key" , "IDictionary.Set[key]" ));
{ Console.Write("\x000D\x000A " ); }
Console.Write(rules.ValidateItemType("value" , "IDictionary.Set[key]" ));
{ Console.Write("\x000D\x000A this[(" ); }
Console.Write(rules.KeyClass);
{ Console.Write(")key]=(" ); }
Console.Write(rules.ItemClass);
{ Console.Write(")value;\x000D\x000A }\x000D\x000A }\x000D\x000A\x000D\x000A" ); }
{ Console.Write(" IDictionaryEnumerator IDictionary.GetEnumerator ()\x000D\x000A " ); }
{ Console.Write(" {\x000D\x000A return new " ); }
Console.Write(rules.Class);
{ Console.Write("DictionaryEnumerator (objectList);\x000D\x000A }\x000D\x000A " ); }
{ Console.Write(" #endregion\x000D\x000A\x000D\x000A\x000D\x000A #region IList" ); }
{ Console.Write(" Implementation\x000D\x000A object IList.this[int index]\x000D\x000A" ); }
{ Console.Write(" {\x000D\x000A set \x000D\x000A {\x000D\x000A " ); }
{ Console.Write(" " ); }
Console.Write(rules.ValidateEntryType("value" , "IList.Set[index]" ));
{ Console.Write("\x000D\x000A " ); }
Console.Write(rules.ValidateKeyIsNull("((DictionaryEntry)value).Key" , "IList.Set[index]" ));
{ Console.Write("\x000D\x000A " ); }
Console.Write(rules.ValidateKeyType("((DictionaryEntry)value).Key" , "IList.Set[index]" ));
{ Console.Write("\x000D\x000A " ); }
Console.Write(rules.ValidateItemType("((DictionaryEntry)value).Value" , "IList.Set[index]" ));
{ Console.Write("\x000D\x000A " ); }
Console.Write(rules.KeyClass);
{ Console.Write(" key = (" ); }
Console.Write(rules.KeyClass);
{ Console.Write(") ((DictionaryEntry) objectList[index]).Key;\x000D\x000A obj" ); }
{ Console.Write("ectList[index] = value;\x000D\x000A objectTable[key] = ((Dic" ); }
{ Console.Write("tionaryEntry)value).Value;\x000D\x000A }\x000D\x000A " ); }
{ Console.Write("get\x000D\x000A {\x000D\x000A return objectList[ind" ); }
{ Console.Write("ex];\x000D\x000A }\x000D\x000A }\x000D\x000A int" ); }
{ Console.Write(" IList.Add(object value)\x000D\x000A {\x000D\x000A " ); }
Console.Write(rules.ValidateEntryType("value" , "IList.Add()" ));
{ Console.Write("\x000D\x000A " ); }
Console.Write(rules.ValidateKeyIsNull("((DictionaryEntry)value).Key" , "IList.Add()" ));
{ Console.Write("\x000D\x000A " ); }
Console.Write(rules.ValidateKeyType("((DictionaryEntry)value).Key" , "IList.Add()" ));
{ Console.Write("\x000D\x000A " ); }
Console.Write(rules.ValidateItemType("((DictionaryEntry)value).Value" , "IList.Add()" ));
{ Console.Write("\x000D\x000A this.Add( (" ); }
Console.Write(rules.KeyClass);
{ Console.Write(")((DictionaryEntry)value).Key, (" ); }
Console.Write(rules.ItemClass);
{ Console.Write(")((DictionaryEntry)value).Value);\x000D\x000A return objectLis" ); }
{ Console.Write("t.Count-1;\x000D\x000A }\x000D\x000A bool IList.Contains(" ); }
{ Console.Write("object value)\x000D\x000A {\x000D\x000A " ); }
Console.Write(rules.ValidateEntryType("value" , "IList.Contains()" ));
{ Console.Write("\x000D\x000A " ); }
Console.Write(rules.ValidateKeyIsNull("((DictionaryEntry)value).Key" , "IList.Contains()" ));
{ Console.Write("\x000D\x000A " ); }
Console.Write(rules.ValidateKeyType("((DictionaryEntry)value).Key" , "IList.Contains()" ));
{ Console.Write("\x000D\x000A " ); }
Console.Write(rules.ValidateItemType("((DictionaryEntry)value).Value" , "IList.Contains()" ));
{ Console.Write("\x000D\x000A return this.Contains((" ); }
Console.Write(rules.KeyClass);
{ Console.Write(")((DictionaryEntry)value).Key);\x000D\x000A }\x000D\x000A " ); }
{ Console.Write(" int IList.IndexOf(object value)\x000D\x000A {\x000D\x000A " ); }
{ Console.Write(" " ); }
Console.Write(rules.ValidateEntryType("value" , "IList.Add()" ));
{ Console.Write("\x000D\x000A " ); }
Console.Write(rules.ValidateKeyIsNull("((DictionaryEntry)value).Key" , "IList.Add()" ));
{ Console.Write("\x000D\x000A " ); }
Console.Write(rules.ValidateKeyType("((DictionaryEntry)value).Key" , "IList.Add()" ));
{ Console.Write("\x000D\x000A " ); }
Console.Write(rules.ValidateItemType("((DictionaryEntry)value).Value" , "IList.Add()" ));
{ Console.Write("\x000D\x000A return this.IndexOf((" ); }
Console.Write(rules.KeyClass);
{ Console.Write(")((DictionaryEntry)value).Key);\x000D\x000A }\x000D\x000A " ); }
{ Console.Write(" void IList.Remove(object value)\x000D\x000A {\x000D\x000A " ); }
{ Console.Write(" " ); }
Console.Write(rules.ValidateEntryType("value" , "IList.Remove()" ));
{ Console.Write("\x000D\x000A " ); }
Console.Write(rules.ValidateKeyIsNull("((DictionaryEntry)value).Key" , "IList.Remove()" ));
{ Console.Write("\x000D\x000A " ); }
Console.Write(rules.ValidateKeyType("((DictionaryEntry)value).Key" , "IList.Remove()" ));
{ Console.Write("\x000D\x000A " ); }
Console.Write(rules.ValidateItemType("((DictionaryEntry)value).Value" , "IList.Remove()" ));
{ Console.Write("\x000D\x000A this.Remove((" ); }
Console.Write(rules.KeyClass);
{ Console.Write(")((DictionaryEntry)value).Key);\x000D\x000A }\x000D\x000A " ); }
{ Console.Write(" void IList.Insert(int index, object value)\x000D\x000A {\x000D\x000A" ); }
{ Console.Write(" " ); }
Console.Write(rules.ValidateEntryType("value" , "IList.Insert()" ));
{ Console.Write("\x000D\x000A " ); }
Console.Write(rules.ValidateKeyIsNull("((DictionaryEntry)value).Key" , "IList.Insert()" ));
{ Console.Write("\x000D\x000A " ); }
Console.Write(rules.ValidateKeyType("((DictionaryEntry)value).Key" , "IList.Insert()" ));
{ Console.Write("\x000D\x000A " ); }
Console.Write(rules.ValidateItemType("((DictionaryEntry)value).Value" , "IList.Insert()" ));
{ Console.Write("\x000D\x000A this.Insert(index, (" ); }
Console.Write(rules.KeyClass);
{ Console.Write(")((DictionaryEntry)value).Key, (" ); }
Console.Write(rules.ItemClass);
{ Console.Write(")((DictionaryEntry)value).Value);\x000D\x000A }\x000D\x000A " ); }
{ Console.Write(" #endregion\x000D\x000A \x000D\x000A\x000D\x000A public" ); }
{ Console.Write(" void CopyTo (Array array, int idx)\x000D\x000A {\x000D\x000A " ); }
{ Console.Write(" objectTable.CopyTo (array, idx);\x000D\x000A }\x000D\x000A" ); }
{ Console.Write("\x000D\x000A public void Insert (int idx, " ); }
Console.Write(rules.KeyClass);
{ Console.Write(" key, " ); }
Console.Write(rules.ItemClass);
{ Console.Write(" value)\x000D\x000A {\x000D\x000A if (idx > Count)\x000D" ); }
{ Console.Write("\x000A throw new ArgumentOutOfRangeException (\x0022inde" ); }
{ Console.Write("x\x0022);\x000D\x000A\x000D\x000A objectTable.Add (key, valu" ); }
{ Console.Write("e);\x000D\x000A objectList.Insert (idx, new DictionaryEntry " ); }
{ Console.Write("(key, value));\x000D\x000A }\x000D\x000A\x000D\x000A publ" ); }
{ Console.Write("ic void Remove (" ); }
Console.Write(rules.KeyClass);
{ Console.Write(" key)\x000D\x000A {\x000D\x000A objectTable.Remove (k" ); }
{ Console.Write("ey);\x000D\x000A objectList.RemoveAt (IndexOf (key));\x000D\x000A" ); }
{ Console.Write(" }\x000D\x000A\x000D\x000A public void RemoveAt (int idx)" ); }
{ Console.Write("\x000D\x000A {\x000D\x000A if (idx >= Count)\x000D\x000A" ); }
{ Console.Write(" throw new ArgumentOutOfRangeException (\x0022index\x0022" ); }
{ Console.Write(");\x000D\x000A\x000D\x000A objectTable.Remove ( ((Dictionary" ); }
{ Console.Write("Entry)objectList[idx]).Key );\x000D\x000A objectList.RemoveA" ); }
{ Console.Write("t (idx);\x000D\x000A }\x000D\x000A\x000D\x000A IEnumerato" ); }
{ Console.Write("r IEnumerable.GetEnumerator ()\x000D\x000A {\x000D\x000A " ); }
{ Console.Write(" return new " ); }
Console.Write(rules.Class);
{ Console.Write("Enumerator (objectList);\x000D\x000A }\x000D\x000A\x000D\x000A " ); }
{ Console.Write(" public int Count\x000D\x000A {\x000D\x000A get " ); }
{ Console.Write("{ return objectList.Count; }\x000D\x000A }\x000D\x000A\x000D\x000A" ); }
{ Console.Write(" public bool IsFixedSize { get { return false; } }\x000D\x000A\x000D" ); }
{ Console.Write("\x000A public bool IsReadOnly { get { return false; } }\x000D\x000A" ); }
{ Console.Write("\x000D\x000A public bool IsSynchronized { get { return false; } " ); }
{ Console.Write("}\x000D\x000A\x000D\x000A public " ); }
Console.Write(rules.ItemClass);
{ Console.Write(" this[int idx]\x000D\x000A {\x000D\x000A get { return" ); }
{ Console.Write(" (" ); }
Console.Write(rules.ItemClass);
{ Console.Write(") ((DictionaryEntry) objectList[idx]).Value; }\x000D\x000A s" ); }
{ Console.Write("et\x000D\x000A {\x000D\x000A if (idx < 0 || i" ); }
{ Console.Write("dx >= Count)\x000D\x000A throw new ArgumentOutOfRangeExc" ); }
{ Console.Write("eption (\x0022index\x0022);\x000D\x000A\x000D\x000A " ); }
Console.Write(rules.KeyClass);
{ Console.Write(" key = (" ); }
Console.Write(rules.KeyClass);
{ Console.Write(") ((DictionaryEntry) objectList[idx]).Key;\x000D\x000A o" ); }
{ Console.Write("bjectList[idx] = new DictionaryEntry (key, value);\x000D\x000A " ); }
{ Console.Write(" objectTable[key] = value;\x000D\x000A }\x000D\x000A " ); }
{ Console.Write(" }\x000D\x000A\x000D\x000A public " ); }
Console.Write(rules.ItemClass);
{ Console.Write(" this[" ); }
Console.Write(rules.KeyClass);
{ Console.Write(" key]\x000D\x000A {\x000D\x000A get { return (" ); }
Console.Write(rules.ItemClass);
{ Console.Write(") objectTable[key]; }\x000D\x000A set\x000D\x000A " ); }
{ Console.Write(" {\x000D\x000A if (objectTable.Contains (key))\x000D\x000A" ); }
{ Console.Write(" {\x000D\x000A objectTable[key] = val" ); }
{ Console.Write("ue;\x000D\x000A objectTable[IndexOf (key)] = new Dic" ); }
{ Console.Write("tionaryEntry (key, value);\x000D\x000A return;\x000D" ); }
{ Console.Write("\x000A }\x000D\x000A Add (key, value);\x000D" ); }
{ Console.Write("\x000A }\x000D\x000A }\x000D\x000A\x000D\x000A " ); }
{ Console.Write(" public ICollection Keys\x000D\x000A {\x000D\x000A ge" ); }
{ Console.Write("t\x000D\x000A {\x000D\x000A ArrayList retList" ); }
{ Console.Write(" = new ArrayList ();\x000D\x000A for (int i = 0; i < obj" ); }
{ Console.Write("ectList.Count; i++)\x000D\x000A {\x000D\x000A " ); }
{ Console.Write(" retList.Add ( ((DictionaryEntry)objectList[i]).Key );\x000D\x000A" ); }
{ Console.Write(" }\x000D\x000A return retList;\x000D\x000A" ); }
{ Console.Write(" }\x000D\x000A }\x000D\x000A\x000D\x000A publi" ); }
{ Console.Write("c ICollection Values\x000D\x000A {\x000D\x000A get\x000D" ); }
{ Console.Write("\x000A {\x000D\x000A ArrayList retList = new " ); }
{ Console.Write("ArrayList ();\x000D\x000A for (int i = 0; i < objectList" ); }
{ Console.Write(".Count; i++)\x000D\x000A {\x000D\x000A " ); }
{ Console.Write("retList.Add ( ((DictionaryEntry)objectList[i]).Value );\x000D\x000A " ); }
{ Console.Write(" }\x000D\x000A return retList;\x000D\x000A " ); }
{ Console.Write(" }\x000D\x000A }\x000D\x000A\x000D\x000A public o" ); }
{ Console.Write("bject SyncRoot\x000D\x000A {\x000D\x000A get { return" ); }
{ Console.Write(" this; }\x000D\x000A }\x000D\x000A\x000D\x000A public int" ); }
{ Console.Write(" IndexOf (" ); }
Console.Write(rules.KeyClass);
{ Console.Write(" key)\x000D\x000A {\x000D\x000A for (int i = 0; i < o" ); }
{ Console.Write("bjectList.Count; i++)\x000D\x000A {\x000D\x000A " ); }
{ Console.Write(" if (((DictionaryEntry) objectList[i]).Key.Equals (key))\x000D\x000A " ); }
{ Console.Write(" {\x000D\x000A return i;\x000D\x000A " ); }
{ Console.Write(" }\x000D\x000A }\x000D\x000A return " ); }
{ Console.Write("-1;\x000D\x000A }\x000D\x000A }\x000D\x000A\x000D\x000A pu" ); }
{ Console.Write("blic class " ); }
Console.Write(rules.Class);
{ Console.Write("DictionaryEnumerator : IDictionaryEnumerator\x000D\x000A {\x000D\x000A" ); }
{ Console.Write(" private int index = -1;\x000D\x000A private ArrayList ob" ); }
{ Console.Write("js;\x000D\x000A\x000D\x000A internal " ); }
Console.Write(rules.Class);
{ Console.Write("DictionaryEnumerator (ArrayList list)\x000D\x000A {\x000D\x000A " ); }
{ Console.Write(" objs = list;\x000D\x000A }\x000D\x000A\x000D\x000A " ); }
{ Console.Write(" public bool MoveNext ()\x000D\x000A {\x000D\x000A " ); }
{ Console.Write(" index++;\x000D\x000A if (index >= objs.Count)\x000D\x000A " ); }
{ Console.Write(" return false;\x000D\x000A\x000D\x000A return " ); }
{ Console.Write("true;\x000D\x000A }\x000D\x000A\x000D\x000A public void R" ); }
{ Console.Write("eset ()\x000D\x000A {\x000D\x000A index = -1;\x000D\x000A" ); }
{ Console.Write(" }\x000D\x000A\x000D\x000A public object Current\x000D\x000A" ); }
{ Console.Write(" {\x000D\x000A get\x000D\x000A {\x000D\x000A" ); }
{ Console.Write(" if (index < 0 || index >= objs.Count)\x000D\x000A " ); }
{ Console.Write(" throw new InvalidOperationException ();\x000D\x000A\x000D\x000A" ); }
{ Console.Write(" return objs[index];\x000D\x000A }\x000D\x000A" ); }
{ Console.Write(" }\x000D\x000A\x000D\x000A DictionaryEntry IDictionaryEnu" ); }
{ Console.Write("merator.Entry\x000D\x000A {\x000D\x000A get\x000D\x000A" ); }
{ Console.Write(" {\x000D\x000A return (DictionaryEntry) Curre" ); }
{ Console.Write("nt;\x000D\x000A }\x000D\x000A }\x000D\x000A\x000D\x000A" ); }
{ Console.Write(" public " ); }
Console.Write(rules.EntryClass);
{ Console.Write(" Entry\x000D\x000A {\x000D\x000A get\x000D\x000A " ); }
{ Console.Write(" {\x000D\x000A return (" ); }
Console.Write(rules.EntryClass);
{ Console.Write(") Current;\x000D\x000A }\x000D\x000A }\x000D\x000A\x000D" ); }
{ Console.Write("\x000A object IDictionaryEnumerator.Key\x000D\x000A {\x000D" ); }
{ Console.Write("\x000A get\x000D\x000A {\x000D\x000A " ); }
{ Console.Write(" return (" ); }
Console.Write(rules.KeyClass);
{ Console.Write(") Entry.Key;\x000D\x000A }\x000D\x000A }\x000D\x000A\x000D" ); }
{ Console.Write("\x000A public " ); }
Console.Write(rules.KeyClass);
{ Console.Write(" Key\x000D\x000A {\x000D\x000A get\x000D\x000A " ); }
{ Console.Write(" {\x000D\x000A return (" ); }
Console.Write(rules.KeyClass);
{ Console.Write(") Entry.Key;\x000D\x000A }\x000D\x000A }\x000D\x000A\x000D" ); }
{ Console.Write("\x000A object IDictionaryEnumerator.Value\x000D\x000A {\x000D" ); }
{ Console.Write("\x000A get\x000D\x000A {\x000D\x000A " ); }
{ Console.Write(" return (" ); }
Console.Write(rules.ItemClass);
{ Console.Write(") Entry.Value;\x000D\x000A }\x000D\x000A }\x000D\x000A" ); }
{ Console.Write("\x000D\x000A public " ); }
Console.Write(rules.ItemClass);
{ Console.Write(" Value\x000D\x000A {\x000D\x000A get\x000D\x000A " ); }
{ Console.Write(" {\x000D\x000A return (" ); }
Console.Write(rules.ItemClass);
{ Console.Write(") Entry.Value;\x000D\x000A }\x000D\x000A }\x000D\x000A" ); }
{ Console.Write(" }\x000D\x000A\x000D\x000A // typed Key, Value properties\x000D\x000A" ); }
{ Console.Write(" public class " ); }
Console.Write(rules.Class);
{ Console.Write("Enumerator : IEnumerator\x000D\x000A {\x000D\x000A private in" ); }
{ Console.Write("t index = -1;\x000D\x000A private ArrayList objs;\x000D\x000A\x000D" ); }
{ Console.Write("\x000A internal " ); }
Console.Write(rules.Class);
{ Console.Write("Enumerator (ArrayList list)\x000D\x000A {\x000D\x000A " ); }
{ Console.Write(" objs = list;\x000D\x000A }\x000D\x000A\x000D\x000A publi" ); }
{ Console.Write("c bool MoveNext ()\x000D\x000A {\x000D\x000A index++;" ); }
{ Console.Write("\x000D\x000A if (index >= objs.Count)\x000D\x000A " ); }
{ Console.Write(" return false;\x000D\x000A\x000D\x000A return true;\x000D" ); }
{ Console.Write("\x000A }\x000D\x000A\x000D\x000A public void Reset ()\x000D" ); }
{ Console.Write("\x000A {\x000D\x000A index = -1;\x000D\x000A }" ); }
{ Console.Write("\x000D\x000A\x000D\x000A public " ); }
Console.Write(rules.EntryClass);
{ Console.Write(" Current\x000D\x000A {\x000D\x000A get\x000D\x000A " ); }
{ Console.Write(" {\x000D\x000A if (index < 0 || index >= objs.Co" ); }
{ Console.Write("unt)\x000D\x000A throw new InvalidOperationException ();" ); }
{ Console.Write("\x000D\x000A\x000D\x000A return new " ); }
Console.Write(rules.EntryClass);
{ Console.Write("(\x000D\x000A (" ); }
Console.Write(rules.KeyClass);
{ Console.Write(")((DictionaryEntry)objs[index]).Key,\x000D\x000A (" ); }
Console.Write(rules.ItemClass);
{ Console.Write(")((DictionaryEntry)objs[index]).Value\x000D\x000A );\x000D" ); }
{ Console.Write("\x000A }\x000D\x000A }\x000D\x000A\x000D\x000A " ); }
{ Console.Write(" object IEnumerator.Current\x000D\x000A {\x000D\x000A g" ); }
{ Console.Write("et\x000D\x000A {\x000D\x000A return new " ); }
Console.Write(rules.EntryClass);
{ Console.Write("(\x000D\x000A (" ); }
Console.Write(rules.KeyClass);
{ Console.Write(")((DictionaryEntry)objs[index]).Key,\x000D\x000A (" ); }
Console.Write(rules.ItemClass);
{ Console.Write(")((DictionaryEntry)objs[index]).Value\x000D\x000A );\x000D" ); }
{ Console.Write("\x000A }\x000D\x000A }\x000D\x000A\x000D\x000A " ); }
Console.Write(rules.EntryClass);
{ Console.Write(" Entry\x000D\x000A {\x000D\x000A get\x000D\x000A " ); }
{ Console.Write(" {\x000D\x000A return Current;\x000D\x000A " ); }
{ Console.Write(" }\x000D\x000A }\x000D\x000A\x000D\x000A public " ); }
Console.Write(rules.KeyClass);
{ Console.Write(" Key\x000D\x000A {\x000D\x000A get\x000D\x000A " ); }
{ Console.Write(" {\x000D\x000A return Entry.Key;\x000D\x000A " ); }
{ Console.Write(" }\x000D\x000A }\x000D\x000A\x000D\x000A public " ); }
Console.Write(rules.ItemClass);
{ Console.Write(" Value\x000D\x000A {\x000D\x000A get\x000D\x000A " ); }
{ Console.Write(" {\x000D\x000A return Entry.Value;\x000D\x000A " ); }
{ Console.Write(" }\x000D\x000A }\x000D\x000A }\x000D\x000A\x000D\x000A" ); }
{ Console.Write("\x000D\x000A" ); }
Console.Write(rules.Namespace.Length>0 ? "}" : "" );
{ Console.Write("\x000D\x000A" ); }
DumpOutput();
Console.SetOut(console);
}
}
}
class OrderedDictionaryRules
{
public string KeyClass { get { return CommandParameter("Key" ); } }
public string ItemClass { get { return CommandParameter("Item" ); } }
public string DictionaryClass { get { return CommandParameter("Dictionary" ); } }
public string Namespace { get { string [] raw=DictionaryClass.Split('.' ); return raw.Length==1 ? DictionaryClass : string .Join("." , raw, 0, raw.Length-1); } }
public string Class { get { string [] raw=DictionaryClass.Split('.' ); return raw.Length==1 ? DictionaryClass : raw[raw.Length-1]; } }
public string EntryClass { get { return Class+"Entry" ; } }
public string TargetSource { get { return DictionaryClass + ".cs" ; } }
public string ValidateKeyIsNull(string instance, string method )
{
return string .Format("if ({0}==null) throw new ArgumentNullException(\"key argument is null at {1}.{2}\");" , instance, Class, method );
}
public string ValidateKeyType(string instance, string method )
{
return string .Format("if (!({0} is {1})) throw new ArgumentException(\"keys argument is \" + {0}.GetType().Name + \" instead of {1} at {2}.{3}\");" , instance, KeyClass, Class, method );
}
public string ValidateItemType(string instance, string method )
{
return string .Format("if (!({0} is {1})) throw new ArgumentException(\"item argument is \" + {0}.GetType().Name + \" instead of {1} at {2}.{3}\");" , instance, ItemClass, Class, method );
}
public string ValidateEntryType(string instance, string method )
{
return string .Format("if (!({0} is {1})) throw new ArgumentException(\"IList entry argument is \" + {0}.GetType().Name + \" instead of {1} at {2}.{3}\");" , instance, "DictionaryEntry" , Class, method );
}
string CommandParameter(string parameter)
{
foreach (string a in System.Environment.GetCommandLineArgs())
if (a.ToLower().StartsWith("/" +parameter.ToLower()+":" )) return a.Substring(parameter.Length+2);
throw new NullReferenceException("/" +parameter+": option required" );
return null ;
}
}
Re[2]: Коллекции в .NET Framework Class Library
Здравствуйте, AsIs, Вы писали:
AI>вот кодогенератор типизированной коллекции для любого фреймоврка
AI>AI>{ Console.Write("\x000D\x000A" ); }
AI> TargetSource=rules.TargetSource;
AI>{ Console.Write("\x000D\x000A\x000D\x000Ausing System;\x000D\x000Ausing System.Collectio" ); }
AI>{ Console.Write("ns;\x000D\x000A\x000D\x000A" ); }
AI>
Бррррррррр. А почему нельзя было написать по простому:
Console.Write(string .Format(@"
using System;
using System.Collections
...
"
Если нам не помогут, то мы тоже никого не пощадим.
Re[3]: Коллекции в .NET Framework Class Library
От:
AsIs
Дата: 30.01.04 19:52
Оценка:
Здравствуйте, IT, Вы писали:
IT>Здравствуйте, AsIs, Вы писали:
AI>>вот кодогенератор типизированной коллекции для любого фреймоврка
AI>>AI>>{ Console.Write("\x000D\x000A" ); }
AI>> TargetSource=rules.TargetSource;
AI>>{ Console.Write("\x000D\x000A\x000D\x000Ausing System;\x000D\x000Ausing System.Collectio" ); }
AI>>{ Console.Write("ns;\x000D\x000A\x000D\x000A" ); }
AI>>
IT>Бррррррррр. А почему нельзя было написать по простому:
IT>IT>Console.Write(string .Format(@"
IT>using System;
IT>using System.Collections
IT>...
IT>"
IT>
так написал кодогенератор кодогенератора
Re[4]: Коллекции в .NET Framework Class Library
Здравствуйте, AsIs, Вы писали:
AI>>>вот кодогенератор типизированной коллекции для любого фреймоврка
AI>так написал кодогенератор кодогенератора
Так надо написать не просто кодогенератор кодогенератора, а кодогенератор кодогенератора с человеческим лицом.
Если нам не помогут, то мы тоже никого не пощадим.
Re[5]: Коллекции в .NET Framework Class Library
Здравствуйте, IT, Вы писали:
AI>>так написал кодогенератор кодогенератора
IT>Так надо написать не просто кодогенератор кодогенератора, а кодогенератор кодогенератора с человеческим лицом.
Пожалуй, стоит написать кодогенератор, который кодогенерирует кодогенератор с человеческим лицом, чтобы он генерировал кодогенератор, который генерирует коллекции. Фухх.
Re[6]: Коллекции в .NET Framework Class Library
Здравствуйте, mikа, Вы писали:
IT>>Так надо написать не просто кодогенератор кодогенератора, а кодогенератор кодогенератора с человеческим лицом.
M>Пожалуй, стоит написать кодогенератор, который кодогенерирует кодогенератор с человеческим лицом, чтобы он генерировал кодогенератор, который генерирует коллекции. Фухх.
да таких кодоненераторов и плагинов уже туева хуча.
* thriving in a production environment *
Re[5]: Коллекции в .NET Framework Class Library
Здравствуйте, _DmitryMS, Вы писали:
_DM>apologies for the crappy English.
А зачем писать по-английски и потом извиняться? Не проще ли писать по-русски?
... << RSDN@Home 1.1.3 beta 2 >>
Есть логика намерений и логика обстоятельств,
последняя всегда сильнее .
Re[3]: Коллекции в .NET Framework Class Library
Здравствуйте, IT, Вы писали:
IT>Бррррррррр. А почему нельзя было написать по простому:
Да такие вещи вообще-то легко реализуются в виде визардо для студии. Нафиг тут программы то писть?
... << RSDN@Home 1.1.3 beta 2 >>
Есть логика намерений и логика обстоятельств,
последняя всегда сильнее .
Re: Коллекции в .NET Framework Class Library
От:
VBez
Дата: 19.03.04 09:52
Оценка:
В статье объяввление BitArray приводится вот таким:
[Serializable()]
public sealed class BitArray : ICollection, ICloneable
Хотя полное вот такое:
[Serializable]
public sealed class BitArray : ICollection, IEnumerable , ICloneable
Но я что-то не могу понять как использовать энумератор.
Если так, то вылетает System.InvalidCastException.
Что нужно прописать вместо byte?
foreach (byte bt in b)
{
Console.WriteLine(bt);
}
Re[2]: Коллекции в .NET Framework Class Library
От:
orangy
Дата: 19.03.04 09:56
Оценка:
Здравствуйте, VBez, Вы писали:
VB>Хотя полное вот такое:
VB>VB>[Serializable]
VB>public sealed class BitArray : ICollection, IEnumerable , ICloneable
VB>
Это не полное, это декомпилированное
public interface ICollection: IEnumerable... << RSDN@Home 1.1.3 beta 2 >>
"Develop with pleasure!"
Re[3]: Коллекции в .NET Framework Class Library
От:
VBez
Дата: 19.03.04 09:59
Оценка:
O>Это не полное, это декомпилированное
Это не декомпилированное — это эмэсдээнное
PS.
А по сути что-то скажешь?
... << RSDN@Home 1.1.3 stable >>
Re[4]: Коллекции в .NET Framework Class Library
Здравствуйте, VBez, Вы писали:
VB> А по сути что-то скажешь?
Легко
Используй bool
... << RSDN@Home 1.1.3 beta 2 >>
"Develop with pleasure!"
Re[5]: Коллекции в .NET Framework Class Library
От:
VBez
Дата: 19.03.04 10:04
Оценка:
O>Легко Используй bool
Ай маладэц.
Пасиба.
... << RSDN@Home 1.1.3 stable >>
Re[6]: Коллекции в .NET Framework Class Library
Здравствуйте, VBez, Вы писали:
VB>Пасиба.
На будущее — типы значений возвращаемые энумератором обычно (но не всегда) совпадают с типом индексера. В частности у BitArray имеется:
public bool this [int index]
Главное исключение из этого правила — Dictionary, его энумератор возвращает DictionaryEntry.
... << RSDN@Home 1.1.3 beta 2 >>
"Develop with pleasure!"
Re: Коллекции в .NET Framework Class Library
От:
VBez
Дата: 19.03.04 15:42
Оценка:
SortedList
...
Как и Hashtable, SortedList является реализацией абстракции «словарь» (IDictionary), но, в отличие от хэш-таблицы, поддерживает упорядоченность данных. Достигается это за счет хранения ключей и данных в двух отсортированных массивах .
...
Что значат выделенные слова?
Вот такой пример показывает, что ключи отсортированы, но значения — нет.
SortedList h = new SortedList();
h.Add(2, "Second" );
h.Add(3, "Third" );
h.Add(1, "First" );
h[4] = "fourth" ;
foreach (object s in h.Keys)
{
Console.WriteLine(s.ToString());
}
foreach (object s in h.Values)
{
Console.WriteLine(s.ToString());
}
Или я не так понимаю?
Пока на собственное сообщение не было ответов, его можно удалить.
Удалить