c# - 如何将未知类型的对象传递给函数
问题描述
是否可以编写一个接受任何类型作为object
参数的函数?
就像是
private bool isItAString(var Input)
{
string example = "example";
return Input.GetType() == example.GetType();
}
关键字在此实例var
中无效,并且它希望它是特定类型的对象。
解决方案
首先说明问题:
给定任意
Input
类型的对象,如果它是一个我们应该返回string
由于.Net中的所有对象都是我们的后代,object
因此我们可以声明Input
为类型Object
并放入
// means you can put string value = Input;
// and value will be assigned
private static bool isItAString(object Input) =>
Input is string;
或者如果我们想要执行精确检查(我们想要Input
类型string
而不是别的)
// Or ... => Input == null || ...
// if we accept null as a valid string
private static bool isItAString(object Input) =>
Input != null && Input.GetType() == typeof(string);
请注意,该var
关键字表示类型推断:我们要求 .net推断所需的类型,而不是明确输入:
// data is of type string[]
var data = new List<int>() {1, 2, 3} // List<int>
.Select(x => x.ToString()) // IEnumerable<string>
.OrderBy(x => x) // IOrderedEnumerable<string>
.ToArray(); // string[]
在你的情况下
private bool isItAString(var Input)
.Net 无法推断实际Input
类型(是object
吗string
??)
推荐阅读
- python - 把原来的函数装饰成点击命令后如何运行?
- java - 连四游戏如何正常输出玩家
- sql-server - 如何在将源定义为 Azure SQL Server 的 NSG 中定义入站安全规则
- android - keytool :在我的生产密钥库中写入 SHA256withRSA 而不是实际的 SHA256
- php - 在 GCP 计算引擎 move_uploaded_file() 不工作
- node.js - 节点 JS 服务器地址不可用
- macos - Apple Script:将文件(从提示中选择)复制到另一个位置
- python - 如何将汤中的特定标签转换为字符串?
- raspberry-pi4 - 是否有 Linux 操作系统的智能眼镜
- bots - 如何让机器人控制我的电报个人聊天