gpt4 book ai didi

c# - 是否可以在运行时将数据类型分配给未知变量

转载 作者:行者123 更新时间:2023-12-02 17:39:06 24 4
gpt4 key购买 nike

我是 c# silverlight-5 初学者,我有一个场景,其中我使用了这样的类节点(作为结构)

   public class Node
{
public Node next, left, right;
public int symbol; // This variable will create problem
public int freq;
}public Node front, rear;

这个类 Node 在另一个 class Huffman 里面,像这样

Class Huffman
{
public class Node
{
public Node next, left, right;
public int symbol; // This variable will create problem
public int freq;
}public Node front, rear;
}

现在我接下来要做的是在 huffman 的构造函数中,我在运行时通过从另一个类调用的构造函数接收变量“processingValue”的数据类型。 因此,processingValue 的数据类型是在运行时由另一个类调用 Huffman 的构造函数时决定的

在 Huffman 构造函数中我必须做这样的事情:

Class Huffman
{
public class Node
{
public Node next, left, right;
public int symbol; // This variable will create problem
public int freq;
}public Node front, rear;

Huffman(AnotherClass object) //The call from another class is Huffman obj = new Huffman(this);
{
temp = new Node();
temp.symbol = (processingValue); //THIS LINE CREATES PROBLEM BECAUSE DATA TYPE OF "symbol" is int and may be data type of processingValue could be "short"/"long"/"UInt"etc.
}
}

有什么方法可以将“symbol”的数据类型转换为“processingValue”的数据类型吗?

我的意思是在 Node Class 中,如果我将符号的数据类型设置为 "Type" 或任何其他类型,然后我在构造函数中更改它的数据类型,使其与数据类型相同加工值(value)?运行时我的意思是它是一个 silverlight 应用程序,我有 comboBox 在运行程序时从有限的数据类型(在 short/int/long/Uint 中)中进行选择,然后控件转到 Huffman 构造函数,其中选择了相应的数据类型组合框

*可以吗? * 非常感谢您的帮助。

最佳答案

您可以使用dynamic 类型来确保symbol 的数据类型实际上是在运行时确定的。

public dynamic symbol;

通过这样做,以下分配将全部有效:

symbol = (long) 100;
symbol = (int) 100;
symbol = (uint) 100;

关于c# - 是否可以在运行时将数据类型分配给未知变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22906337/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com