C#中的变体类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11046622/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Variant Type in C#
提问by whytheq
VBA (and I assume VB) has a Variant type which I believe takes up more memory, but covers various data types.
VBA(我假设 VB)有一个 Variant 类型,我认为它占用更多内存,但涵盖了各种数据类型。
Is there an equivalent in c# ?
c# 中是否有等价物?
In a windows form say I had the following, how would I amend the type of z so that it runs ok
在 Windows 窗体中说我有以下内容,我将如何修改 z 的类型以使其正常运行
private void uxConvertButton_Click(object sender, EventArgs e)
{
int x = 10;
byte j = (byte)x;
upDateRTB(j);
long q = (long)x;
upDateRTB(q);
string m = x.ToString();
upDateRTB(m);
}
void upDateRTB(long z) {
MessageBox.Show(this,"amount; "+z);
}
采纳答案by Darin Dimitrov
void upDateRTB(object z) {
MessageBox.Show(this, "amount; " + Convert.ToString(z));
}
回答by Erno
The dynamic keyword or the object type could give you the variant behavior you want but:
dynamic 关键字或对象类型可以为您提供所需的变体行为,但是:
In this case I'd change the function to:
在这种情况下,我会将函数更改为:
void upDateRTB(string z) {
MessageBox.Show(this,"amount; " + z);
}
Because that's all the method needs.
因为这就是方法所需要的。
回答by Ribtoks
If you're talking about "variant"type in c#, take a look at dynamictype in .net 4.0
如果您在谈论c# 中的“变体”类型,请查看dynamic.net 4.0中的类型
But for solving your task it would be enough to use z.ToString()in your MessageBox.Show
但是,解决你的任务就足够使用z.ToString()您的MessageBox.Show
回答by Petar Ivanov
"amount; "+zimplicitly calls the ToString method on z.
So you can use type object:
"amount; "+z在 上隐式调用 ToString 方法z。所以你可以使用类型object:
void upDateRTB(object z) {
MessageBox.Show(this,"amount; "+z);
}
You can also use dynamic, but I don't see the point:
您也可以使用动态,但我不明白这一点:
void upDateRTB(dynamic z) {
MessageBox.Show(this,"amount; "+z);
}
回答by Me.Name
An object parameter would accept all, but if you'd like to keep the variables strongly typed (and avoid boxing in the process), you could use generics:
一个对象参数会接受所有,但如果你想保持变量的强类型(并避免在过程中装箱),你可以使用泛型:
void upDateRTB<T>(T z) {
MessageBox.Show(this,"amount; "+ Convert.ToString(z));
}
The method calls could remain precisely the same, because the compiler can resolve the generic type based on the given parameter.
方法调用可以保持完全相同,因为编译器可以根据给定的参数解析泛型类型。

