|
Afternoon all !
I have populated a list with various animal objects - 'Cat, Dog, Lion, Tiger....'
I am stepping through the list in order to have them call specific methods.
The Cat & Dog object both have the same method Pet(). None of the other animals in the list have this method.
If i implement 2 seperate statments -
foreach (Cat thisCat in zooAnimals.OfType<Cat>())
{
thisCat.pet();
}
foreach (Dog thisDog in zooAnimals.OfType<Dog>())
{
thisDog.pet();
}
the code will work fine.
I would like to know for my own benefit if there's a way to concatenate these statements into 1
i.e
foreach (Cat thisCat in zooAnimals.OfType<Cat>() || Dog thisDog in zooAnimals.OfType<Dog>())
{
thisCat.pet();
thisDog.pet();
}
Thanks in advance
Neil
|
|
|
|
|
The way to do this is to create an interface called IPettable with a single method Pet() .
You then implement this interface for Cat, Dog and any other animal you might want to Pet.
Your code then becomes:
foreach (IPettable pettableAnimal in zooAnimals.OfType<IPettable>())
{
pettableAnimal.pet();
}
|
|
|
|
|
You could do this by implementing an extra interface and then iterating over this interface. Like this:
interface IHasPetMethod
{
void pet();
}
foreach ( IHasPetMethod hasPetMethod in zooAnimals.OfType<IHasPetMethod> )
{
hasPetMethod.pet();
}
This makes the intention of the programmer somewhat clearer (if there is a pet() method, then call it). But compared with your original approach, it's largely a matter of taste and coding style.
Regards
Thomas
www.thomas-weller.de
Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning. Programmer - an organism that turns coffee into software.
modified on Wednesday, December 3, 2008 11:26 AM
|
|
|
|
|
Not really - because OfType<T> takes a specific type you can't interchange between Dog and Cat unless they share some common type (other than 'Animal' which I'm assuming is your base type).
My preference would be that Cat and Dog both implement an IPet interface:
<br />
internal interface IPet<br />
{<br />
void Pet();<br />
}<br />
so that when you're doing your look you call
<br />
foreach (IPet pet in zooAnimals.Oftype<ipet>())<br />
{<br />
pet.Pet();<br />
}<br />
</ipet>
FWIW, I assume you're using yield return in your OfType<t> - it's more efficient than creating an intermediary IEnumerable object to store the results before returning them?
HTH
It definitely isn't definatley
|
|
|
|
|
|
Maybe it's about time I looked at C# 3.0 - and convinced my clients to go down the same road!!
It definitely isn't definatley
|
|
|
|
|
There are genreally two diffrerent approaches to this, and either might make sense in this case.
1. (As suggested already in the thread) You can create in interface IPettable and make the Cat and Doc implement the interface. Then you can check if the object implements the interface:
foreach (Animal animal in zooAnimals) {
IPettable pettable = animal as IPettable;
if (pettable != null) pettable.Pet();
}
2. You can make a common base type for domestic animals:
public abstract class DomesticAnimal : Animal {
public virtual void Pet();
}
Now you make the Cat and Doc classes inherit DomesticAnimal instead of Animal, and implement the Pet method. You can also implement the Pet method in the DomesticAnimal class if the implementation is the same for Cat and Dog.
foreach (Animal animal in zooAnimals) {
DomesticAnimal domestic = animal as DomesticAnimal;
if (domestic != null) domestic.Pet();
}
Despite everything, the person most likely to be fooling you next is yourself.
|
|
|
|
|
Deusche Version: (für die deutschsprachigen unter uns)
Hi,
Ich möchte eine Anwendung schreiben die aus einem Windows Dienst (Server) und einer Desktopanwendung (Client) besteht. Der Dienst erstellt dabei eine Instanz von einr Klasse, die selbstständig, mit meheren Ressourcen, über dem SerielPort und TCP/IP, arbeitet. Die Desktopanwendung soll sich nun irgend wie mit dem Dienst in Verbindung setzten und dieses Instance abrüfen können um bestimmte Events zu behandel, Eigenschaften abzufragen und methoden auszuführen.
Soweit ich weiß gibt es da eine möglichkeit mittels remoting. Aber bei dem was ich bisher gesehen hab, wird das Object, erst durch den Abruf durch eines Clients erstellt. Ich brauche das Object aber bereits beim Start des Dienstes und nicht erst wenn es irgend jemand abruft.
Daher meine Frage: Wie ist es möglich ein Objekt welches ich selbst erstellt hab, einer Desktopanwendung zur Verfügung zu stelllen ?
--------------------------------------------------
english version:
Hi,
I want to write an application with a windows service as server and a desktop application as client. The service creates an instance of class which works independently with serveral resources on the SerielPort and the TCP/IP. The desktop application must be able to connect to the service and get the afore created instance and may handle events, invoke properties and perform methods.
As far as I know there is a possibility using Remoting. But with what I've seen so far, the instance will first created on a demand by a client. But I already need the object on the start of the service and not only when someone demand it.
Thats why my question: How is it possible to expose or provide an instance, which I've created on my own, for a desktop application ?
|
|
|
|
|
It sounds like the resource classes and the remoting classes should be independent of one another. When the service starts it can create and manage whatever resources it's designed to manage and then use remoting simply as a message channel that clients can use to connect and issue commands to the service.
|
|
|
|
|
Hello,
I need to produce Hammersley sequence for n-dim in C#. Does anyone have any expertise?
Thanks
|
|
|
|
|
|
Hi all,
I want to calculate the homography assuming i have 4 points in the original image and 4 points in the resulted image.
x' = xH where x' is the points in the resulted image, H is the homography and x is points in the original image. Please help! Thanks!
|
|
|
|
|
What are points (in this context), what's the function, what have you tried so far?
modified 12-Sep-18 21:01pm.
|
|
|
|
|
I am trying to distort the image to my preference. In this case, the points are simply (x1,y1) to (x4,y4). These points will be mapped to my preferred points. Hence calculating the Homograph. The problem here is I couldn't get the 3x3 Homograph.
|
|
|
|
|
|
Take a look at this, particularly slide 14. The effect I hope to get is the same as the ppt provided.
www.csd.uwo.ca/courses/CS837b/lectures/cs837_lec03_mosaic.ppt
Thanks.
|
|
|
|
|
I haven't seen an article here at CP that does this sort of thing (which doesn't mean it doesn't exist). Basically you could pick any image warping algorithm and modify it in a way that does the image retification thing.
I don't have any samples, though
regards
modified 12-Sep-18 21:01pm.
|
|
|
|
|
As the presentation explains rather well, there are two ways to solve this:
- analytically (slides 15-20), which is fine in a perfect world;
- by optimization, e.g. least square approximation, (slides 21-23) which is best if the input isn't very accurate.
It will take some math and some programming skills to create a working solution.
I don't know an out-of-the-box solution. Google may know one.
|
|
|
|
|
yup, tried that. somehow somewhere it goes wrong. i'm not very expert in c#. hence, required some help any expert willing to help?
Thanks!
|
|
|
|
|
The problem can be programmed in any language you choose; there is nothing particular about it that makes it a better or worse fit for C#.
You could visit Jeffrey Martin's web site and find his contact info there. I trust he has code in whatever language that solves it.
|
|
|
|
|
I'm not sure how to help you without just doing all the work for you. You've provided a ppt that has all the maths you need. If you can't work out how to turn this math into code, then I guess this is beyond you for now. But, it's really pretty easy, you just need to sit down and think it through.
If you posted your code, I'd be happy to look at it and compare it to the algorithm provided.
Christian Graus
Driven to the arms of OSX by Vista.
|
|
|
|
|
i m trying to configure db in remote server through C# , locally it is configuring but in Remote Server db is is not creating. Following is the code
public bool createDB(object sServerName, String sDBName,object sAdminUname,object sAdminPwd)
{
object objServerName;
objServerName = sServerName;
SQLDMO.SQLServer gSQLServerDMO = new SQLDMO.SQLServer();
SQLDMO.Database nDatabase = new SQLDMO.Database();
SQLDMO.DBFile nDBFileData = new SQLDMO.DBFile();
SQLDMO.LogFile nLogFile = new SQLDMO.LogFile();
try
{
gSQLServerDMO.Connect(objServerName, sAdminUname, sAdminPwd);
nDatabase.Name = sDBName;
nDBFileData.Name = sDBName;
nDBFileData.PhysicalName = gSQLServerDMO.Registry.SQLDataRoot + "\\DATA\\" + sDBName + "_Data.mdf";
nDBFileData.PrimaryFile = true;
nDBFileData.Size = 2;
nDBFileData.FileGrowthType = SQLDMO.SQLDMO_GROWTH_TYPE.SQLDMOGrowth_MB;
nDBFileData.FileGrowth = 1;
//Adding DBFile object
nDatabase.FileGroups.Item("PRIMARY").DBFiles.Add(nDBFileData);
nLogFile.Name = sDBName + "_Log";
nLogFile.PhysicalName = gSQLServerDMO.Registry.SQLDataRoot + "\\DATA\\" + sDBName + "_Log.ldf";
nLogFile.Size = 2;
nDatabase.TransactionLog.LogFiles.Add(nLogFile);
gSQLServerDMO.Databases.Add(nDatabase);
return true;
}
catch (Exception sqlDBException)
{
String errSqlDBexception = sqlDBException.Message;
return false;
}
finally
{
gSQLServerDMO.DisConnect();
}
}
//Section for creating the database login and user in the above created Database.//
public bool Createdatabaselogin(String sDataSource, string databsename, String sScriptName, String sUserId, String sPwd, string loginName, string loginpass)
{
try
{
string sqlConnectionString = "Data Source=" + sDataSource + ";Initial Catalog=" + databsename + ";USER ID=" + sUserId + "; PWD=" + sPwd + ";Persist Security Info=True";
SqlConnection conn = new SqlConnection(sqlConnectionString);
Server server = new Server(new ServerConnection(conn));
string sqlquerylogin = "EXEC sp_addlogin '" + loginName + "','" + loginpass + "'";
string sqlqueryuser = "EXEC sp_adduser '" + loginName + "','" + loginName + "','db_owner'";
if (!server.Logins.Contains(loginName))
{
server.ConnectionContext.ExecuteNonQuery(sqlquerylogin);
}
server.ConnectionContext.ExecuteNonQuery(sqlqueryuser);
return true;
}
catch (Exception ex)
{
String error_str = ex.ToString();
return false;
}
}
What is wrong in this , can anyone suggest some idea?
|
|
|
|
|
hi friends
how to get current console application path
thanks
|
|
|
|
|
l.laxmikant wrote: how to get current console application path
That is very vague. Are you looking for the startup directory or the current working directory? The latter can be found in the Environment class.
xacc.ide - now with TabsToSpaces support IronScheme - 1.0 beta 1 - out now! ((lambda (x) `((lambda (x) ,x) ',x)) '`((lambda (x) ,x) ',x))
|
|
|
|
|
Environment.CurrentDirectory
Environment.CommandLine
Simon
|
|
|
|