c# - 如何将字符串数组转换为泛型数组类型,同时允许非数组和数组作为类的泛型类型参数?
问题描述
我有一个Option<T>
非常适合从字符串转换的任何类型,现在我正在尝试将其扩展为涵盖Option<T[]>
(即,Option<int[]>)
.恐怕我可能会遇到这个问题,因为我的腰带下有太多 C++ 模板。包装我的绕过看似不足的 C# 泛型。我可以检测到 T 何时是一个数组,但是我无法使用typeof(T).GetElementType()
.
我想我可能处于那些 XY 问题山谷之一,我只是从错误的方向来到这里,看不到上升的路径。任何想法如何解除限制?我已经尝试了所有我能想到的方法,并在过去的几天里试图弄清楚是否可以畅通无阻。我要补充一点,我可以安排在转换之前将逗号分隔的字符串解析为字符串数组。下面的代码是我尝试过的一些代码的简化摘录。
using System;
using System.Collections.Generic;
namespace StackOverflowCS
{
internal static class ConversionExtensionMethods
{
internal static T ChangeType<T>(this object obj)
{
try
{
return (T)Convert.ChangeType(obj, typeof(T));
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
internal static T ChangeType<T>(this object[] objects)
{
try
{
if (!typeof(T).IsArray) throw new Exception("T is not an array type.");
var converted = new object[objects.Length];
foreach (var item in objects)
{
// AFAIK, converstion requires compile time knowledge of T.GetElementType(),
// but this won't compile.
converted.Add(item.ChangeType<typeof(T).GetElementType())>
}
return (T)converted; // And this won't compile either.
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
}
internal class Option<T>
{
public T Value;
public Option() {}
// This works fine for non-arrays
public bool SetValue(string valueString)
{
try
{
Value = valueString.ChangeType<T>();
}
catch (Exception e)
{
Console.WriteLine(e);
return false;
}
return true;
}
// I think I am in an XY problem valley here.
public bool SetValue(string[] valueStrings)
{
try
{
if (!typeof(T).IsArray)
{
throw new Exception("T is not an array type.");
}
// The crux of my problem is I can't seem to write pure generic code in C#
var convertedElements = new List<!!!Cannot use typeof(T).GetElementType() here!!!>();
foreach (var item in valueStrings)
{
// The crux of my problem is I can't seem to write pure generic code in C#
convertedElements.Add(!!!Cannot use typeof(T).GetElementType() here!!!);
}
}
catch (Exception e)
{
Console.WriteLine(e);
return false;
}
return true;
}
}
public class Program
{
static void Main(string[] args)
{
var opt = new Option<int>(); // Works fine.
var integerList = new Option<int[]>();
integerList.SetValue("this,that,whatever"); // This fails at run-time.
foreach (var item in integerList.Value)
{
Console.WriteLine(item);
}
Console.ReadKey();
}
}
}
解析器(未显示)可以检测
Opt:1,2,3
or
Opt:"short sentence",word,"string with quotes\" in it"
等形式的参数。
我宁愿不让解析器尝试找出 Opt 选项的数组元素是什么类型。该Option<T>.SetValue(string[] strings)
功能应该能够处理。
我什至还没有尝试过测试/实现 `Options<List>,尽管我怀疑这会容易得多。
解决方案
您可以尝试这样做以允许非数组和数组泛型类型参数:
using System;
using System.Linq;
设置值(字符串值字符串)
public bool SetValue(string valueString)
{
try
{
if ( typeof(T).IsArray ) throw new Exception("T is an array type.");
Value = (T)Convert.ChangeType(valueString, typeof(T));
}
catch ( Exception e )
{
Console.WriteLine(e);
return false;
}
return true;
}
设置值(字符串 [] 值字符串)
public bool SetValue(string[] valueStrings)
{
try
{
if ( !typeof(T).IsArray ) throw new Exception("T is not an array type.");
var thetype = typeof(T).GetElementType();
var list = valueStrings.Select(s => Convert.ChangeType(s, thetype)).ToList();
var array = Array.CreateInstance(thetype, list.Count);
for (int index = 0; index < list.Count; index++ )
array.SetValue(list[index], index);
Value = (T)Convert.ChangeType(array, typeof(T));
}
catch ( Exception e )
{
Console.WriteLine(e);
return false;
}
return true;
}
考试
static void Main(string[] args)
{
// Non array
var opt = new Option<int>();
opt.SetValue("10");
Console.WriteLine(opt.Value);
Console.WriteLine();
// Array
var integerList = new Option<int[]>();
integerList.SetValue(new[] { "1", "2", "3" });
foreach ( var item in integerList.Value )
Console.WriteLine(item);
// End
Console.ReadKey();
}
输出
10
1
2
3
推荐阅读
- excel - 对数组求和
- yocto - 如何将 BeagleBoneBlack 的 pasm PRU 编译器集成到 Yocto 中
- sql - 我需要 sql position() 中的文本长度
- android - HM10 与 Arduino 和 Android BLE 之间的低功耗蓝牙大数据传输
- oop - 如何使用包含 where 的抽象多方法?
- javascript - 如何使用className(javascript)在div标签上应用onclick
- reactjs - React 没有渲染任何东西?
- shell - zsh - 如何引用以多个其他变量动态命名的变量?
- css - 修复了header,下面有视差英雄图,平滑滚动iOS和无JS
- c++ - 在 OpenCV 中未正确设置像素