简体   繁体   English

我可以使用隐式转换器将常见值类型(例如Int32)的类型转换扩展到我的自定义类型吗?

[英]Can i extend type cast of common value types (like Int32) with implicid converter to my custom type?

What if i need some kind of reference type wrapper for Int32 (the database Id for example). 如果我需要某种类型的Int32引用类型包装器(例如数据库ID),该怎么办? How can i convert Int32 to my class implicitly? 如何将Int32隐式转换为类?

Create a static implicit converter operator: 创建一个静态隐式转换器运算符:

public class MyClass
{
    ....
    static public implicit operator MyClass(int value)
    {
        // Create a new instance of your class using the value.
    }
    ...
}

Once created, you can do something like this: 创建完成后,您可以执行以下操作:

MyClass myInstance = 48;

For more information, see MSDN: Using Conversion Operators (C# Programming Guide) 有关更多信息,请参见MSDN: 使用转换运算符(C#编程指南)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 转换为值类型“Int32”失败 - The cast to value type 'Int32' failed 转换为值类型'Int32'失败空值LINQ - The cast to value type 'Int32' failed null value LINQ 转换为值类型“Int32”失败,因为实现值为null - The cast to value type 'Int32' failed because the materialized value is null 转换为值类型“Int32”失败,因为物化值为 null - The cast to value type 'Int32' failed because the materialized value is null Linq错误:强制转换为值类型'Int32',因为物化值为null - Linq error: The cast to value type 'Int32' failed because the materialized value is null 转换为值类型“Int32”失败,因为通过加载网格视图实现的值为空 - The cast to value type 'Int32' failed because the materialized value is null via loading Grid View 转换为值类型'int32'失败,因为实例化值为null - Cast to value type 'int32' failed because the materialized value is null 显示无法创建类型“”的常量值。 在这种情况下,仅支持基本类型(例如Int32,String和Guid) - Showing Unable to create a constant value of type ''. Only primitive types ('such as Int32, String, and Guid') are supported in this context 对于 CLR 类型“Int32[]”,找不到到关系类型的映射 - No mapping to a relational type can be found for the CLR type 'Int32[]' 无法创建类型为“结算类型”的常量值。 在这种情况下,仅支持基本类型(例如Int32,String和Guid) - Unable to create a constant value of type 'Closure type'. Only primitive types ('such as Int32, String, and Guid') are supported in this context
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM