C# 如何将int值强制转换为与char等效的泛型类型参数?
我是泛型新手,在实现一个小的自我实践代码时遇到了一些问题 我正在创建一个链表。我希望它存储char或int值。因此,我决定让实现变得通用:C# 如何将int值强制转换为与char等效的泛型类型参数?,c#,generics,casting,linked-list,type-conversion,C#,Generics,Casting,Linked List,Type Conversion,我是泛型新手,在实现一个小的自我实践代码时遇到了一些问题 我正在创建一个链表。我希望它存储char或int值。因此,我决定让实现变得通用: public class Node<T> where T : struct, IConvertible { public Node<T> next = null; public T data = default(T); public Node(T value) { this.data = value; } }
public class Node<T> where T : struct, IConvertible
{
public Node<T> next = null;
public T data = default(T);
public Node(T value) { this.data = value; }
}
公共类节点,其中T:struct,IConvertible
{
公共节点next=null;
公共T数据=默认值(T);
公共节点(T值){this.data=value;}
}
我有一种方法,通过生成[33127]范围内的随机值来创建链表,将值转换为T指定的类型(例如,如果生成86,T为Char,则要存储在链表节点中的值为“V”;如果T为Int32,则值仅为86)。我面临两个问题:
static Node<IConvertible> CreateList<T>(int len) where T : struct, IConvertible
{
Random r = new Random((int)DateTime.Now.Ticks);
T value = (T)r.Next(33, 127); // Problem #1
Node<T> head = new Node<T>(value);
Node<T> n = head;
for (int i = 1; i < len; i++)
{
n.next = new Node<T>(value);
n = n.next;
}
return head; // Problem #2
}
静态节点CreateList(int len),其中T:struct,IConvertible
{
Random r=新随机((int)DateTime.Now.Ticks);
T值=(T)r.Next(33127);//问题#1
节点头=新节点(值);
节点n=头部;
对于(int i=1;i
这些是问题:
1) 通常这是可能的:(int)value=(char)r.Next(33127)。为什么如果T是char类型,编译器会说“无法将类型‘int’转换为‘T’”,即使我指定了“where T:struct,IConvertible”
2) “无法将类型“LinkedList.Node
”隐式转换为“LinkedList.Node
”。如果T是Int32或Char,并且两者都实现了IConvertible,那么如何将节点
或节点
转换为节点
非常感谢!使用
T value = (T)Convert.ChangeType(r.Next(33, 127), typeof(T));
您使用
Random
生成一些数据与使用泛型有点不一致。我将两者分开,如下所示:
static Node<T> CreateList<T>(int len, Func<T> dataProvider) where T : struct, IConvertible
{
Node<T> head = new Node<T>(dataProvider());
Node<T> n = head;
for (int i = 1; i < len; i++)
{
n.next = new Node<T>(dataProvider());
n = n.next;
}
return head;
}
静态节点CreateList(int len,Func dataProvider),其中T:struct,IConvertible
{
节点头=新节点(dataProvider());
节点n=头部;
对于(int i=1;i
呼叫代码:
Random r = new Random();
Node<char> list = CreateList(10, () => (char)r.Next(33, 127));
Random r=new Random();
Node list=CreateList(10,()=>(char)r.Next(33127));
第二个问题是
节点
不被结构对节点
的约束所允许。只需返回一个节点
。即使从节点
中删除结构
约束,也不可能返回节点
,因为泛型类不支持差异。问题就是T可以是任何结构,例如Guid、SByte…或自定义的新结构。虽然我们可以确定T是struct
和IConvertible
,但不必有显式的强制转换操作符
public static explicit operator AnyStruct(int i)
第二个问题是将节点
转换为节点
。任何列表
列表都不能转换为列表
我们需要的是接口上的协方差声明:INode
。然后可以将INode
转换为INode