|
Friends:
I defined a method with a generic value type parameter as follows, but it does not compile (Operator '-' cannot be applied to operands of type 'T' and 'T'; Operator '>' cannot be applied to operands of type 'T' and 'T').
//Declaration
public class Algos
{
public bool CompValues <t> (T t1, T t2) //the generic sign after CompValues was deleted automatically by the website
{
T dif;
dif = t1 - t2;
if(dif > t1)
return true;
else
return false;
}
}
//Calling
Algos al = new Algos();
al.CompValues<int>(5, 3); //the generic sign enclosing "int" after CompValues was deleted automatically by the website
Whether I add constraints or not :"where T: struct" and/or "where T: IComparable<t>", it does not compile. Why?
Thanks!
-- modified at 14:30 Friday 20th July, 2007
Sheng
|
|
|
|
|
|
Kevin:
I does NOT compile. You can try. Or I have to add some "using" reference?
Sheng
|
|
|
|
|
You might want to re-read Kevin's post. What you want to do, at least how your doing it, isn't possible!
You're assuming that a minus operation is possible on ANY TWO OBJECTS you give this code and that's just not the case. THAT'S what the compiler is trying to tell you! Your code, if it were to compile, leaves open the possibility of
dif = SqlConnection - SqlConnection, which, obviously, isn't valid.<br />
<br />
<br />
<br />
<div class="ForumSig"><small><a href="http://www.codeproject.com/scrapbook/ForumGuidelines.asp">A guide to posting questions on CodeProject</a>[<a href="http://www.codeproject.com/scrapbook/ForumGuidelines.asp" target="_blank" title="New Window">^</a>]</small><br><br />
<font color="Blue">Dave Kreskowiak<br />
Microsoft MVP<br />
Visual Developer - Visual Basic<br> 2006, 2007</font><br />
</div>
|
|
|
|
|
Yes. Did you read the links? It's not compilable. You cannot use operator < with generics. It's a limitation. It's possible with C++ but not with .NET.
Kevin
|
|
|
|
|
Okey! I give up trying. The constraint clause "where T: struct" isnt' working either. The constraint clause should have allowed to specify particular types, for example: "where T: System.ValueType". In fact, it does not. It's a deficiency of C# language.
Guys, thanks!
Sheng
|
|
|
|
|
You really need to go back and read the Generics section again. The constraints WHERE clause only works at the class level, not the method level. Such as when making a custom collection of objects.
public class EmployeeList<T> where T: Employee, IEmployee, IComparable<T>, new()
See this[^], and this[^] for examples.
|
|
|
|
|
Hi Dave.
I find his question interessting, and I wonder if this might be possible?
public bool CompValues (T t1, T t2)
{
bool result = false;
if(typeof(t1) == typeof( Value Type here))
{
ValueType var1 = (t1 as ValueType);
ValueType var2 = (t2 as ValueType);
}
else if...
else
{
throw new Exeption("Invalid comparison type.");
}
return result;
}
Or perhaps check type of T against typeof(IComparable) ?
Best regards!
-Larantz-
|
|
|
|
|
It's possible, but when you replace ValueType with your actual type, like int , you really haven't gained anything. This would result in you doing what is already being done. Overloading the Compare method to handle each supported type.
He's trying to use Generics to do something it doesn't support. Since the Value types all implement IComparable already, it should have been written like that:
public int CompareValues(IComparable v1, IComparable v2)
.
.
.
But, again, this already exists is each value, so what he's trying to write is redundant.
|
|
|
|
|
Hi, this is my first post on here so we'll see how it goes.
I am trying to write a method that uses a number of thread to populate an object and then return the object. The problem is that I never know when the threads are finished. I thought about having a counter and it will add when the thread finishes, and then have a Timer check every few seconds and see if the numbers match; however, the it is still a hack and I cannot return my object in the timer event. Any ideas?
public IApplicationPrivilegeCollection GetAllUserPrivileges(string userName)
{
Precondition.NotNullArgument(userName, "userName");
IDatabaseInfoCollection databaseInfoCollection = _databaseInfoRepository.getAllDatabases();
IApplicationPrivilegeCollection applicationPrivilegeCollection = new ApplicationPrivilegeCollection();
int applicationCount = 0;
foreach (IDatabaseInfo databaseInfo in databaseInfoCollection)
{
BackgroundWorker worker = new BackgroundWorker();
IApplicationPrivilege list = new ApplicationPrivilege();
worker.DoWork += delegate(object sender, DoWorkEventArgs e)
{
worker = sender as BackgroundWorker;
list = GetUserPrivilege(userName, (IDatabaseInfo)e.Argument);
}
;
worker.RunWorkerCompleted += delegate(object sender, RunWorkerCompletedEventArgs e)
{
applicationPrivilegeCollection.Add(list);
applicationCount++;
};
worker.RunWorkerAsync(databaseInfo);
}
return applicationPrivilegeCollection;
}
|
|
|
|
|
Your design doesn't make any sense. Your GetAllUserPrivileges method is designed to be a blocking method but then you set off multiple async threads inside it to perform the work.
Try a design where GetAllUserPrivileges does NOT block and you fire an event that contains the desired result object as an Event argument.
|
|
|
|
|
I am not sure I understand you. What do you mean by it being a blocking method? I am new to threading and am actually just using a BackgroundWorker to make it easier.
I think I know what you mean by having a result object; however, the method runs fine right now if I just put a while loop in it and wait for all the threads to finish. I just need a nicer way to detect if all the threads are finished.
I don't understand why you think my design doesn't make sense. I need to set off multiple threads inside a foreach because that is the whole point of using threads here.
|
|
|
|
|
dilucidate wrote: I am not sure I understand you.
dilucidate wrote: What do you mean by it being a blocking method?
dilucidate wrote: I am new to threading
dilucidate wrote: I don't understand why you think my design doesn't make sense.
Text messages are not a good format for discussing a topic as complex as threading. There are good resources available for developers that want to "understand" how and why to properly use threads. An old book that I found very useful was Advanced Windows by Jeffery Richter. Also I have seen several people give a link to a web site with a threading tutorial. Perhaps Google can find it for you.
dilucidate wrote: I am new to threading and am actually just using a BackgroundWorker to make it easier.
"Easier" is not how I would describe your code. Have you ever heard of the K.I.S.S. principle? It means Keep It Simple Stupid.
|
|
|
|
|
Please suggest me proper method to make my Panel recieve Input Focus.
My Requirement is that I have 2 buttons, followed by a Panel and then a List.
I should be able to transfer the focus from First Btn, 2nd Btn, Then Panel and finally the ListBox. Everything is fine but I cannot get the Panel to recieve Keyboard Focus.
I'm using .NET 2.0 SDK.
Thanks
PS: I know that .NET 3.0 has Control.Focusable Property
|
|
|
|
|
Try deriving a control from Panel, and in the constructor, call base.SetStyle(ControlStyles.Selectable, true) .
|
|
|
|
|
Thanks Judah Himango Works As Expected.
|
|
|
|
|
I want to serialize an array of objects, using the SOAP formatter. However, when serializing the second object, I get an exception that says I cannot add the same object twice to a serialization info. I wrote a small application to demonstrate the problem:
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;
using System.Xml;
using System.Runtime.Serialization.Formatters.Soap;
namespace Serialization
{
[Serializable]
public class MyObject:ISerializable
{
public Int32 idx=0;
public MyObject(Int32 i)
{
idx=i;
}
public virtual void GetObjectData(SerializationInfo info,StreamingContext context)
{
info.AddValue("Idx",idx);
}
}
[Serializable]
class ObjectList: ISerializable
{
public List<MyObject> TheList;
public ObjectList()
{
TheList=new List<MyObject>(10);
MyObject tmp=new MyObject(1);
TheList.Add(tmp);
tmp=new MyObject(2);
TheList.Add(tmp);
}
public virtual void GetObjectData(SerializationInfo info,StreamingContext context)
{
Int32 i=0;
for(i=0;i<2;i++)
{
if(TheList[i]!=null)
{
TheList[i].GetObjectData(info,context);
}
}
}
}
class Program
{
static void Main(string[] args)
{
ObjectList MyObjectList=new ObjectList();
FileStream WriteStream=new FileStream("test.xml",FileMode.Create);
SoapFormatter bfor=new SoapFormatter();
bfor.Serialize(WriteStream,MyObjectList);
}
}
}
In the sample I create a class MyObject. Objects of type MyObject are stored in an ObjectList object, which essentially is a wrapper around a LIST<myobject> generic List object.
I have no idea what I'm doing wrong. I did not find any samples on how to handle array serialization. Please note that the application I develop is far more complex than this. Therefore I do not want to use automatic serialization. I use the SOAP formatter because it is easier to debug. Later I will switch to the binary formatter.
Tanks in advance for your advice.
Rudolf Heijink
|
|
|
|
|
Rudolf Jan Heijink wrote: ObjectList MyObjectList=new ObjectList();
try this:
List<MyObject> list = new List<MyObject>();<br />
bfor.Serialize(WriteStream, list);<br />
|
|
|
|
|
Thank you very much for your suggestion.
Unfortunately, your suggestion does not work with the SOAP formmatter. The SOAP formatter seems not to support generic types. With the Binary formatter it seems to work, at least no exceptions or error messages.
Still, I do not like it. I still think it is quite normal to serialize a number of objects. Another thing is that you should not invoke the Soap formatter more than once, because it generates XML headers. (i tried to do this)
I also think there is a difference betwee a class containing al List and maybe other objects (as I will need in my application) and a list. So, I'm not happy yet. Thanks anway.
Rudolf Heijink
|
|
|
|
|
I did some additional tests. It seems the problem has nothing to do with lists, but possibly there is a bug in .NET. If I try to serialize two objects of the same type, I get the error message that I cannot serialize the same object twice. It mey be an error in the translation of the .NET error messages. I cannot check that. I have a Dutch Windows version trepresenting all .NET errors in Dutch.
Below the code to demonstrate the problem:
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;
using System.Xml;
using System.Runtime.Serialization.Formatters.Soap;
namespace Serialization
{
[Serializable]
public class MyObject:ISerializable
{
public Int32 idx=0;
public MyObject(Int32 i)
{
idx=i;
}
internal MyObject(SerializationInfo info,StreamingContext context)
{
idx=info.GetInt32("Idx");
}
public virtual void GetObjectData(SerializationInfo info,StreamingContext context)
{
info.AddValue("Idx",idx);
}
}
[Serializable]
class ObjectList: ISerializable
{
MyObject object1;
MyObject object2;
public ObjectList()
{
object1=new MyObject(1);
object2=new MyObject(2);
}
protected ObjectList(SerializationInfo info,StreamingContext context)
{
object1=new MyObject(info,context);
object2=new MyObject(info,context);
}
public virtual void GetObjectData(SerializationInfo info,StreamingContext context)
{
object1.GetObjectData(info,context);
object2.GetObjectData(info,context);
}
}
class Program
{
static void Main(string[] args)
{
ObjectList MyObjectList=new ObjectList();
FileStream WriteStream=new FileStream("test.xml",FileMode.Create);
SoapFormatter bfor=new SoapFormatter();
MyObject Object1=new MyObject(1);
MyObject object2=new MyObject(2);
bfor.Serialize(WriteStream,MyObjectList);
}
}
}
Rudolf Heijink
|
|
|
|
|
|
Sad story,
I think I understand much more now why things went wrong in my application. I will write an article about it for codeproject, so coming soon.
Thanks anyway for your help.
Rudolf Heijinbk
|
|
|
|
|
how do i program a form window (in c#) to come above the taskbar when ControlBox property is set to false as it slides under the taskbar.
|
|
|
|
|
Hi all,
I has just create an add-in for Visual Studio .NET 2005. I want to create an setup for that add-in so that I can share it to my friends. But I don't know how to do it. Please help me.
Thanks a lot.
imagic
|
|
|
|
|
This article[^] talks about creating an add-in for VS as well as creating a setup project for the add-in, allowing it to be installed on other machines with Visual Studio.
|
|
|
|