问题描述
假设我这样做会很方便:
Hypothetically it'd be handy for me to do this:
foo.GetColumnValues(dm.mainColumn, int)
foo.GetColumnValues(dm.mainColumn, string)
GetColumns 方法将根据传递的类型在其中调用不同的方法.
where the GetColumns method will call a different method inside depending on the type passed.
是的,我可以将它作为一个布尔标志或类似的东西来做,我只是想知道是否有办法传递这个,然后问:
Yes, I could do it as a boolean flag or similar, I just wondered if there was a way to perhaps pass this, and then ask:
typeof(arg[1]) 或类似...
typeof(arg[1]) or similar...
我还可以覆盖方法、使用泛型等 - 我知道有不同的方法可以做到这一点,我只是好奇这是否可行.
推荐答案
有两种常见的方法.首先,你可以通过System.Type
There are two common approaches. First, you can pass System.Type
object GetColumnValue(string columnName, Type type)
{
// Here, you can check specific types, as needed:
if (type == typeof(int)) { // ...
这将被称为:int val = (int)GetColumnValue(columnName, typeof(int));
另一种选择是使用泛型:
The other option would be to use generics:
T GetColumnValue<T>(string columnName)
{
// If you need the type, you can use typeof(T)...
这具有避免装箱和提供某种类型安全的优点,可以这样调用:int val = GetColumnValue(columnName);
This has the advantage of avoiding the boxing and providing some type safety, and would be called like: int val = GetColumnValue<int>(columnName);
这篇关于在 C# 中只传递一个类型作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!