English 中文(简体)
如何将非致命的类型转换为无效的类型?
原标题:How to convert a non-nullable type to a nullable type?

是否可将仅在操作时间已知的非致命价值类型转换为无效? 换言之:

public Type GetNullableType(Type t)
{
    if (t.IsValueType)
    {
        return typeof(Nullable<t>);
    }
    else
    {
        throw new ArgumentException();
    }
}

显然,<代码>return项目有错误。 是否有办法这样做? <代码>Type.MakeGenericType 方法似乎很有希望,但我不知道如何获得一个未指明的通用<代码>Type的标语,代表Nullable<T>。 任何想法?

最佳回答

页: 1

注:Nullable<><>strong> no, 所提供的任何论据均为无约束的通用类型;就更复杂的实例而言,请添加对应体,即:KeyValuePair<>,Tuple<>,>

问题回答

你走在正确的轨道上。 为此:

if (t.IsValueType)
{
    return typeof(Nullable<>).MakeGenericType(t);
}
else
{
    throw new ArgumentException();
}
Type GetNullableType(Type type) {
    // Use Nullable.GetUnderlyingType() to remove the Nullable<T> wrapper
    // if type is already nullable.
    type = Nullable.GetUnderlyingType(type);
    if (type.IsValueType)
        return typeof(Nullable<>).MakeGenericType(type);
    else
        return type;
} 

最容易的解决办法是归还第一批基因组的主食。 因此,在这个例子中,一个可以更改的日期? 随着财产类型的恢复,我需要将其转换为时间类型,以便添加到数据表上。 这应当与否? 并且是双重的? 等等。

if (Nullable.GetUnderlyingType(prop.PropertyType) != null) {
  tb.Columns.Add(prop.Name, prop.PropertyType.GenericTypeArguments.First().UnderlyingSystemType);
} else {
  tb.Columns.Add(prop.Name, prop.PropertyType);
}




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签