my Code is :
using System;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
namespace IEnumerable
{
public class MyEnumerable<T> : IEnumerable<T>
{
public MyEnumerable(T[] items)
{
this.items = items;
}
public IEnumerator<T> GetEnumerator()
{
return new NestedEnumerator(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
// The enumerator definition.
class NestedEnumerator : IEnumerator<T>
{
public NestedEnumerator(MyEnumerable<T> coll)
{
Monitor.Enter(coll.items.SyncRoot);
this.index = -1;
this.coll = coll;
}
public T Current
{
get { return current; }
}
object IEnumerator.Current
{
get { return Current; }
}
public bool MoveNext()
{
if (++index >= coll.items.Length)
{
return false;
}
else
{
current = coll.items[index];
return true;
}
}
public void Reset()
{
current = default(T);
index = 0;
}
public void Dispose()
{
try
{
current = default(T);
index = coll.items.Length;
}
finally
{
Monitor.Exit(coll.items.SyncRoot);
}
}
private MyEnumerable<T> coll;
private T current;
private int index;
}
private T[] items;
}
public class EntryPoint
{
static void Main()
{
MyEnumerable<int> integers = new MyEnumerable<int>(new int[] { 1, 2, 3, 4 });
foreach (int n in integers)
{
Console.WriteLine(n);
}
}
}
}
I am implementing this piece of code But i get an error. Can anybody help me what to do to error free this code? please help.
My Errors are :
1->'IEnumerable' is a 'namespace' but is used like a 'type'
2->'IEnumerable.MyEnumerable' does not implement interface member 'System.Collections.IEnumerable.GetEnumerator()'. 'IEnumerable.MyEnumerable.GetEnumerator()' cannot implement 'System.Collections.IEnumerable.GetEnumerator()' because it does not have the matching return type of 'System.Collections.IEnumerator'.
The error is likely that you're using IEnumerable as your namespace when it's already a type in the system.
This means that your references to IEnumerable are refering to the current namespace and not the IEnumerable you're meaning to use (System.Collections.IEnumerable).
Try changing your namespace to something else.
Listen to what the compiler is telling you and change your namespace to something sensible (like BlingBlingWoo)
...
using System.Collections.Generic;
namespace BlingBlingWoo
{
public class MyEnumerable<T> : IEnumerable<T>
...
Whats happening here is:
Error : 'IEnumerable' is a 'namespace' but is used like a 'type'
You are trying to use the type IEnumerable, but you've created a namespace called IEnumerable and so the compiler things its a namespace.
Related
I've had homework to do for my programming lectures, and I don't know that is my solution correct?
I've had to implement stack by the list, but I don't know am I understood it correctly.
Sorry for my English :)
using System;
using System.Collections.Generic;
using System.Text;
namespace Zad._20
{
class Element
{
public String value;
public Element previous;
public Element(String value) {
this.value = value;
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace Zad._20
{
class Stack
{
private Element top;
public Stack() {
top = null;
}
public void Push(Element e) {
e.previous = top;
top = e;
}
public void Pop() {
top = top.previous;
}
public void Print() {
while(top != null) {
Console.WriteLine(top.value);
top = top.previous;
}
}
}
}
It seems, that you are trying to implement Stack<T> via LinkedList (well known classical problem), not List; if you insist on List<T>
the code will be quite simple. Your code rewritten to List<T>:
// <T> - let's have a generic stack, e.g. MyStack<int> or MyStack<String>
public class MyStack<T> {
// List<T> in which we store the stack's items
private List<T> m_Items = new List<T>();
// Nothing to write home about; we can safely drop this constructor
public MyStack() {}
public void Push(T item) {
// Just add item to the items
m_Items.Add(item);
}
public T Pop() {
// We can't Pop an item from the empty stack
if (m_Items.Count <= 0)
throw new InvalidOperationException("Stack is empty");
else {
// Take the last item
T result = m_Items[m_Items.Count - 1];
// Remove it (the last item) from the list
m_Items.RemoveAt(m_Items.Count - 1);
// Return the last item
return result;
}
}
public void Print() {
// Print out all the items in reversed order
for (int i = m_Items.Count - 1; i >= 0; --i)
Console.WriteLine(m_Items[i]);
}
}
I would like to convert a blocking IEnumerable (possibly infinite) into messages sent to an Actor. What is the best way to do this? I am currently attempting to create a Task within an actor on PreStart and inside the task have it send messages to but it doesn't seem to be working.
I've read some pages about preferring to use PipeTo to wrap a Task but that seems to only be used to retrieve a single result rather than have a separate process continually sending values.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Akka.Actor;
namespace Junk
{
public class Program
{
public static void Main()
{
var system = ActorSystem.Create("my-system");
var actor = system.ActorOf(Props.Create(() => new Manager()));
Console.ReadLine();
}
}
public class Manager : ReceiveActor
{
private Task _task;
public Manager() {
Receive<uint>(msg => { Console.WriteLine($"received {msg}"); });
}
protected override void PreStart() {
Console.WriteLine($"{Self} - PreStart --------------");
startTask();
}
private void startTask() {
_task = Task.Factory.StartNew(() => {
BlockingEnumerable source = new BlockingEnumerable();
Console.WriteLine($"task starting loop -------------");
foreach (uint v in source) {
Self.Tell(v);
}
});
}
}
public class BlockingEnumerable : IEnumerable<uint>
{
public IEnumerator<uint> GetEnumerator() { return new BlockingEnumerator(); }
IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }
}
public class BlockingEnumerator : IEnumerator<uint>
{
private uint value = 0;
public uint Current => value;
object IEnumerator.Current => Current;
public void Dispose() { }
public bool MoveNext() { Thread.Sleep(2000); value += 1; return true; }
public void Reset() { value = 0; }
}
}
I need to see a property of an object which is of a generic type, without knowing the specific type:
foreach(var n in Nodes)
{
if(n.GetType().GetGenericTypeDefinition() == typeof(VariableNode<>))
{
if((n as VariableNode<>).Variable == myVar) //obviously this does not work
{
toRemove.Add(n);
}
}
}
So, what would be the most elegant way to check the property "Variable" ? (variable is a reference type)
Thanks!
EDIT:
Def of Node:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using KSPComputer.Types;
using KSPComputer.Connectors;
namespace KSPComputer.Nodes
{
[Serializable]
public abstract class Node
{
public SVector2 Position;
public int InputCount
{
get
{
return inputs.Count;
}
}
public int OutputCount
{
get
{
return outputs.Count;
}
}
public FlightProgram Program { get; private set; }
private Dictionary<string, ConnectorIn> inputs;
private Dictionary<string, ConnectorOut> outputs;
public KeyValuePair<string, ConnectorIn>[] Inputs
{
get
{
return inputs.ToArray();
}
}
public KeyValuePair<string, ConnectorOut>[] Outputs
{
get
{
return outputs.ToArray();
}
}
public Node()
{
Position = new SVector2();
inputs = new Dictionary<string, ConnectorIn>();
outputs = new Dictionary<string, ConnectorOut>();
}
internal virtual void Init(FlightProgram program)
{
Program = program;
OnCreate();
}
protected void In<T>(string name, bool allowMultipleConnections = false)
{
var connector = new ConnectorIn(typeof(T), allowMultipleConnections);
connector.Init(this);
inputs.Add(name, connector);
}
protected void Out<T>(string name, bool allowMultipleConnections = true)
{
var connector = new ConnectorOut(typeof(T), allowMultipleConnections);
connector.Init(this);
outputs.Add(name, connector);
}
protected void Out(string name, object value)
{
ConnectorOut o;
if (outputs.TryGetValue(name, out o))
{
if (o.Connected)
{
o.SendData(value);
}
}
}
protected ConnectorOut GetOuput(string name, bool connected = true)
{
ConnectorOut o;
if (outputs.TryGetValue(name, out o))
{
if (o.Connected || !connected)
{
return o;
}
}
return null;
}
protected ConnectorIn In(string name)
{
ConnectorIn o;
if (inputs.TryGetValue(name, out o))
{
return o;
}
return null;
}
public void UpdateOutputData()
{
RequestInputUpdates();
OnUpdateOutputData();
}
protected virtual void OnUpdateOutputData()
{ }
protected virtual void OnCreate()
{ }
protected void RequestInputUpdates()
{
foreach (var i in inputs.Values)
{
i.FreshData = false;
}
foreach (var i in inputs.Values)
{
if (!i.FreshData)
{
i.RequestData();
}
}
}
public IEnumerable<Connector> GetConnectedConnectors()
{
return (from c in inputs.Values where c.Connected select c as Connector).Concat(from c in outputs.Values where c.Connected select c as Connector);
}
public IEnumerable<Connector> GetConnectedConnectorsIn()
{
return (from c in inputs.Values where c.Connected select c as Connector);
}
public IEnumerable<Connector> GetConnectedConnectorsOut()
{
return (from c in outputs.Values where c.Connected select c as Connector);
}
}
}
Definition of VariableNode:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KSPComputer;
using KSPComputer.Nodes;
using KSPComputer.Connectors;
using KSPComputer.Variables;
namespace KSPComputer.Nodes
{
[Serializable]
public class VariableNode<T> : ExecutableNode
{
internal Variable Variable { get; private set; }
internal void SetVariable(Variable variable)
{
this.Variable = variable;
}
protected override void OnCreate()
{
In<T>("Set");
Out<T>("Get");
}
protected override void OnExecute(ConnectorIn input)
{
Variable.Value = In("Set").Get<T>();
ExecuteNext();
}
protected override void OnUpdateOutputData()
{
Out("Get", Variable.Value);
}
}
}
It looks like you should be able to use reflection:
foreach(var n in Nodes)
{
if(n.GetType().GetGenericTypeDefinition() == typeof(VariableNode<>))
{
if(n.GetType().GetProperty("Variable").GetValue(n, null) == myVar)
{
toRemove.Add(n);
}
}
}
The other solution would be defining a non-generic base class for your VariableNode then you can put your non-generic property there, and finally you can easily cast your node as the base or interface and get the value of your property. Having a non generic base is quite popular practice.
I have such work to(lab) do:
... information about events must e written in some files, which must be determinated by attached to this class attribute.
Wgat a sense is in this attribute? what it must to do?
All lab is "Write generic class of list with opportunity to generate events when you call some class methods. Information about events must e written in some files, which must be determinated by attached to this class attribute.
I don't understand reason of using in this lab attribute, please help me.
Here I have written sample generic class of list
Here are two files:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lab7
{
public class MyListClass<T>: IEnumerable<T>
{
public delegate void MyDelegate();
public event MyDelegate AddEvent;
public event MyDelegate RemEvent;
List<T> list;
public T this[int index]
{
get { return list[index]; }
set { list[index] = value; }
}
public void Add(T item)
{
list.Add(item);
if (AddEvent != null)
AddEvent();
}
public void Remove(T item)
{
list.Remove(item);
if (RemEvent != null)
RemEvent();
}
public void RemoveAt(int index)
{
list.RemoveAt(index);
if (RemEvent != null)
RemEvent();
}
public MyListClass()
{
list = new List<T>();
}
public MyListClass(List<T> list)
{
this.list = list;
}
public IEnumerator<T> GetEnumerator()
{
return list.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return list.GetEnumerator();
}
#region Events
/*static void AddHandler()
{
Console.WriteLine("Объект добавлен в коллекцию");
}
static void RemoveHandler()
{
Console.WriteLine("Объект удалён из коллекции");
}*/
#endregion
}
}
and here is main class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lab7
{
class Program
{
static void Main(string[] args)
{
MyListClass<int> lst = new MyListClass<int>();
lst.AddEvent +=new MyListClass<int>.MyDelegate(AddHandler);
lst.RemEvent+=new MyListClass<int>.MyDelegate(RemoveHandler);
lst.Add(2542);
lst.Add(785);
lst.RemoveAt(1);
}
static void AddHandler()
{
Console.WriteLine("Объект добавлен в коллекцию");
}
static void RemoveHandler()
{
Console.WriteLine("Объект удалён из коллекции коллекцию");
}
}
}
Sorry for my bad English. I don't say to do all lab for me, only give me ideas, and examples how to write this)
The question is difficult to understand, but I think it wants you do decorate your class or methods with an attribute which points to a file in which some sort of event data is stored.
So it would look something like this:
class SomeClass
{
[MyEventInfoAttribute(EventFile = "c:\\blah\\events.foo")]
void SomeMethod()
{
}
}
So you need to define an attribute:
public class MyEventInfoAttribute : Attribute
{
public property string EventFile { get; set; }
}
How you store the event information and implement the events is up to you.
Your code would have to use reflection to discover the attribute on the methods.
For example:
class SomeClass
{
[MyEventInfoAttribute(EventFile = "c:\\blah\\events.foo")]
void SomeMethod()
{
Type type = typeof(SomeClass);
MethodInfo method = type.GetMethod("SomeMethod");
object[] atts = method.GetCustomAttributes();
if (atts.Length > 0)
{
if (atts[0] is MyEventInfoAttribute)
{
string fileName = ((MyEventInfoAttribute)atts[0]).EventFile;
... now open the file, read the event info, and use it ...
}
}
}
}
This is a simplified example to give you an idea of the direction to go in.
This is kind of hard to explain, I hope my English is sufficient:
I have a class "A" which should maintain a list of objects of class "B" (like a private List). A consumer of class "A" should be able to add items to the list. After the items are added to the list, the consumer should not be able to modify them again, left alone that he should not be able to temper with the list itself (add or remove items). But he should be able to enumerate the items in the list and get their values. Is there a pattern for it? How would you do that?
If the question is not clear enough, please let me know.
To prevent editing the list or its items you have to make them immutable, which means you have to return a new instance of an element on every request.
See Eric Lippert's excellent series of "Immutability in C#": http://blogs.msdn.com/ericlippert/archive/tags/Immutability/C_2300_/default.aspx (you have to scroll down a bit)
As many of these answers show, there are many ways to make the collection itself immutable.
It takes more effort to keep the members of the collection immutable. One possibility is to use a facade/proxy (sorry for the lack of brevity):
class B
{
public B(int data)
{
this.data = data;
}
public int data
{
get { return privateData; }
set { privateData = value; }
}
private int privateData;
}
class ProxyB
{
public ProxyB(B b)
{
actual = b;
}
public int data
{
get { return actual.data; }
}
private B actual;
}
class A : IEnumerable<ProxyB>
{
private List<B> bList = new List<B>();
class ProxyEnumerator : IEnumerator<ProxyB>
{
private IEnumerator<B> b_enum;
public ProxyEnumerator(IEnumerator<B> benum)
{
b_enum = benum;
}
public bool MoveNext()
{
return b_enum.MoveNext();
}
public ProxyB Current
{
get { return new ProxyB(b_enum.Current); }
}
Object IEnumerator.Current
{
get { return this.Current; }
}
public void Reset()
{
b_enum.Reset();
}
public void Dispose()
{
b_enum.Dispose();
}
}
public void AddB(B b) { bList.Add(b); }
public IEnumerator<ProxyB> GetEnumerator()
{
return new ProxyEnumerator(bList.GetEnumerator());
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
The downside of this solution is that the caller will be iterating over a collection of ProxyB objects, rather than the B objects they added.
EDIT: Added support for edition contexts. Caller can only add elements inside an edition context. You can aditionally enforce that only one edition context can be created for the lifetime of the instance.
Using encapsulation you can define any set of policies to access the inner private member. The following example is a basic implementation of your requirements:
namespace ConsoleApplication2
{
using System;
using System.Collections.Generic;
using System.Collections;
class B
{
}
interface IEditable
{
void StartEdit();
void StopEdit();
}
class EditContext<T> : IDisposable where T : IEditable
{
private T parent;
public EditContext(T parent)
{
parent.StartEdit();
this.parent = parent;
}
public void Dispose()
{
this.parent.StopEdit();
}
}
class A : IEnumerable<B>, IEditable
{
private List<B> _myList = new List<B>();
private bool editable;
public void Add(B o)
{
if (!editable)
{
throw new NotSupportedException();
}
_myList.Add(o);
}
public EditContext<A> ForEdition()
{
return new EditContext<A>(this);
}
public IEnumerator<B> GetEnumerator()
{
return _myList.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
public void StartEdit()
{
this.editable = true;
}
public void StopEdit()
{
this.editable = false;
}
}
class Program
{
static void Main(string[] args)
{
A a = new A();
using (EditContext<A> edit = a.ForEdition())
{
a.Add(new B());
a.Add(new B());
}
foreach (B o in a)
{
Console.WriteLine(o.GetType().ToString());
}
a.Add(new B());
Console.ReadLine();
}
}
}
You basically want to avoid to give away references to the class B items. That's why you should do a copy of the items.
I think this can be solved with the ToArray() method of a List object. You need to create a deep-copy of the list if you want to prevent changes.
Generally speaking: most of the times it is not worthwhile to do a copy to enforce good behaviour, especially when you also write the consumer.
public class MyList<T> : IEnumerable<T>{
public MyList(IEnumerable<T> source){
data.AddRange(source);
}
public IEnumerator<T> GetEnumerator(){
return data.Enumerator();
}
private List<T> data = new List<T>();
}
The downside is that a consumer can modify the items it gets from the Enumerator, a solution is to make deepcopy of the private List<T>.
It wasn't clear whether you also needed the B instances themselves to be immutable once added to the list. You can play a trick here by using a read-only interface for B, and only exposing these through the list.
internal class B : IB
{
private string someData;
public string SomeData
{
get { return someData; }
set { someData = value; }
}
}
public interface IB
{
string SomeData { get; }
}
The simplest that I can think of is return a readonly version of the underlying collection if editing is no longer allowed.
public IList ListOfB
{
get
{
if (_readOnlyMode)
return listOfB.AsReadOnly(); // also use ArrayList.ReadOnly(listOfB);
else
return listOfB;
}
}
Personally though, I would not expose the underlying list to the client and just provide methods for adding, removing, and enumerating the B instances.
Wow, there are some overly complex answers here for a simple problem.
Have a private List<T>
Have an public void AddItem(T item) method - whenever you decide to make that stop working, make it stop working. You could throw an exception or you could just make it fail silently. Depends on what you got going on over there.
Have a public T[] GetItems() method that does return _theList.ToArray()