المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : Array of class with implicit conversion [modified]



C# Programming
08-18-2009, 02:58 AM
I've probably just been sat in front of this monitor for far too long today (about 14 hours so far http://www.barakasoft.com/script/Forums/Images/smiley_confused.gif) but I can't figure this out!

Consider this struct which is nothing more than an int wrapper:public struct MyStruct
{
private int _Value;

private MyStruct(int value)
{
_Value = value;
}

public static implicit operator int(MyStruct instance)
{
return instance._Value;
}
public static implicit operator MyStruct(int value)
{
return new MyStruct(value);
}

public int Value
{
get { return _Value; }
}
}I can treat an instance as an int until trying to work with an array or list that expects an int[]:MyStruct instance0 = 0;
MyStruct instance1 = 1;
MyStruct instance2 = 2;
MyStruct[] myStructArray = new MyStruct[] { instance1, instance2 };
List intList = new List();
intList.Add(instance0);

/* Cannot convert from 'MyStruct[]' to 'System.Collections.Generic.IEnumerable'*/
intList.AddRange(myStructArray);
/* Cannot implicitly convert type 'MyStruct[]' to 'int[]'*/
int[] intArray = myStructArray;Is there any workaround for this (apart from sleep http://www.barakasoft.com/script/Forums/Images/smiley_laugh.gif )?

I've just found this blog (http://blog.mavadat.net/2008/05/c-covariance-and-contravariance.html)[^ (http://blog.mavadat.net/2008/05/c-covariance-and-contravariance.html)] that says it can be done, but only with reference types

Dave
BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn (http://www.codeproject.com/Members/Luc-Pattyn))
Visual Basic is not used by normal people so we're not covering it here. (Uncyclopedia (http://uncyclopedia.org/wiki/.NET))
Why are you using VB6? Do you hate yourself? (Christian Graus (http://www.codeproject.com/script/Membership/View.aspx?mid=6556))

modified on Monday, August 17, 2009 6:52 PM