标签: implicit-cast

为什么允许从超类到子类的隐式转换?

有人可以告诉我为什么用"// Compiles"编译的行,以及为什么带"//不编译"的行没有?

我不明白为什么A可以隐含地转换为B,而不是相反.

public class SomeClass {

 static public void Test() {
  AClass a = new AClass();
  BClass b = new BClass();

  a = b; // Compiles
  b = a; // Doesn't compile
 }
}

public class AClass {
 public void AMethod() { 
     Console.WriteLine("AMethod");
 }
}

public class BClass : AClass { 
 public void BMethod() {
  Console.WriteLine("BMethod");
 }
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

.net c# inheritance type-conversion implicit-cast

5
推荐指数
3
解决办法
4811
查看次数

c#编译器是否会执行多个隐式转换以从一种类型转换到另一种类型?

假设您有自己的类如下:

public sealed class StringToInt { 
    private string _myString; 
    private StringToInt(string value) 
    { 
        _myString = value; 
    } public static implicit operator int(StringToInt obj) 
    { 
        return Convert.ToInt32(obj._myString); 
    } 
    public static implicit operator string(StringToInt obj) 
    { 
        return obj._myString; 
    } 
    public static implicit operator StringToInt(string obj) 
    { 
        return new StringToInt(obj); 
    } 
    public static implicit operator StringToInt(int obj) 
    { 
        return new StringToInt(obj.ToString()); 
    } 
}
Run Code Online (Sandbox Code Playgroud)

那么您是否可以编写如下代码:

MyClass.SomeMethodThatOnlyTakesAnInt(aString);
Run Code Online (Sandbox Code Playgroud)

没有它声明没有从字符串到int的隐式转换?

[是的,我可以亲自测试一下,但我想我会把它放在那里,看看所有大师们都要说的话]

c# casting implicit-cast

4
推荐指数
1
解决办法
1294
查看次数

C#中的隐式数组转换

我有以下类定义了隐式转换运算符:

class A
{
    ...
}
class B
{
    private A m_a;

    public B(A a)
    {
        this.m_a = a;
    }

    public static implicit operator B(A a)
    {
        return new B(a);
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,我可以隐含地将A转换为B.

但为什么我不能隐含地将A []强制转换为B []?

static void Main(string[] args)
{
    // compiles
    A a = new A();
    B b = a;

    // doesn't compile
    A[] arrA = new A[] {new A(), new A()};
    B[] arrB = arrA;
}
Run Code Online (Sandbox Code Playgroud)

谢谢,Malki.

c# arrays operator-overloading implicit-cast

4
推荐指数
2
解决办法
1万
查看次数

自动转换出错

class Sample
{
public:
  Sample();
  Sample(int i);
  Sample(Sample& s);
  ~Sample();
};

Sample::Sample()
{
  cout<<"Default constructor called\n";
}

Sample::Sample(int i)
{
  cout<<"1-argument constructor called\n";
}

Sample::Sample(Sample& s)
{
  cout<<"Copy constructor called\n";
}

Sample::~Sample()
{
  cout<<"Destructor called\n";
}

void Fun(Sample s)
{

}

int main()
{
  Sample s1;
  Fun(5);

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

我期望隐式转换为5.但是,当我编译上面的代码时,我得到以下错误:

main.cpp:7:8: error: no matching function for call to ‘Sample::Sample(Sample)’
main.cpp:7:8: note: candidates are:
Sample.h:10:3: note: Sample::Sample(Sample&)
Sample.h:10:3: note:   no known conversion for argument 1 from ‘Sample’ to ‘Sample&’
Sample.h:9:3: …
Run Code Online (Sandbox Code Playgroud)

c++ implicit-cast

4
推荐指数
1
解决办法
117
查看次数

C++模板和歧义问题

我有一个指针类的子集,如下所示:

template <typename T>
struct Pointer
{
     Pointer();
     Pointer(T *const x);
     Pointer(const Pointer &x);
     template <typename t>
     Pointer(const Pointer<t> &x);

     operator T *() const;
};
Run Code Online (Sandbox Code Playgroud)

最后一个构造函数的目标是允许传递Pointer一个子类,或者基本上可以隐式转换为的任何类型T *.这个实际规则只能由构造函数的定义强制执行,而编译器实际上无法通过声明单独解决它.如果我删除它,并尝试传递Pointer<Sub>给构造函数Pointer<Base>,我会得到一个编译错误,尽管可能的路径通过operator T *().

虽然它解决了上述问题,但却创造了另一个问题.如果我有一个重载函数,其中一个重载占用a Pointer<UnrelatedClass>而另一个占用Pointer<BaseClass>,并且我尝试用a调用它Pointer<SubClass>,我在两个重载之间得到一个模糊性,当然,意图是后一个重载将被调用.

有什么建议?(希望我足够清楚)

c++ templates ambiguity implicit-cast ambiguous-call

3
推荐指数
1
解决办法
1201
查看次数

即使我有一个隐式强制转换运算符(在asp mvc app中),也会抛出异常转换异常

我创建了一个mvc模型类,其中一个属性是'MyObject'类型.它还有一个System.ComponentModel.DataAnnotations.StringLength属性.

MyObject作为隐式转换运算符,因此它基本上可以用作字符串:

public static implicit operator string(MyObject o){...}
public static implicit operator MyObject(string sValue){...}
Run Code Online (Sandbox Code Playgroud)

出于某种奇怪的原因,这是一个asp mvc问题吗?我问,因为我知道在大多数情况下隐式转换工作正常,我可以例如将该属性分配给字符串值,它可以正常工作.

编辑-好吧,我知道为什么错误是发生:
这是因为StringLength.IsValid()方法需要一个对象作为参数,所以中投实际上是从对象去字符串,而不是从MyObject的串,所以这可以解释为什么我的隐式强制转换运算符未被调用.但是如何解决这个问题呢?

这一切都正常,直到我在我的模型中的属性上放置System.ComponentModel.DataAnnotations.StringLength属性,然后当视图从提交按钮发出帖子时,我得到了异常:

[InvalidCastException:无法将类型为'StrataSpot.Shared.Models.Email'的对象强制转换为'System.String'.]
System.ComponentModel.DataAnnotations.StringLengthAttribute.IsValid(Object value)+34
System.Web.Mvc.d__1. MoveNext()+56 System.Web.Mvc.DefaultModelBinder.OnPropertyValidated(ControllerContext controllerContext,ModelBindingContext bindingContext,PropertyDescriptor propertyDescriptor,Object value)+203 System.Web.Mvc.DefaultModelBinder.BindProperty(ControllerContext controllerContext,ModelBindingContext bindingContext,PropertyDescriptor propertyDescriptor)+413
System.Web.Mvc.DefaultModelBinder.BindProperties(ControllerContext controllerContext,ModelBindingContext的BindingContext)90
System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext controllerContext,ModelBindingContext的BindingContext,对象模型)383
System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext,ModelBindingContext bindingContext)+1048
System.Web .Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext,ModelBindingContext bindingContext)+280
System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext,ParameterDescriptor parameterDescriptor)+257
System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext,ActionDescriptor actionDescriptor)+ 109
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext,字符串actionName)314 System.Web.Mvc.Controller.ExecuteCore()105 System.Web.Mvc.ControllerBase.Execute(RequestContext的RequestContext的)39
的System.Web .Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext)+7
System.Web.Mvc.<> c__DisplayClass8.b__4()+ 34 System.Web.Mvc.Async.<> c__DisplayClass1.b__0() 21 System.Web.Mvc.Async.<> c__DisplayClass8 1.<BeginSynchronous>b__7(IAsyncResult _) +12 System.Web.Mvc.Async.WrappedAsyncResult1.End()59 System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult的asyncResult)44
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndPro cessRequest(IAsyncResult的结果)7
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()8678910 System.Web.HttpApplication.ExecuteStep(IExecutionStep步骤,布尔逻辑completedSynchronously)155

asp.net-mvc implicit-cast implicit-conversion asp.net-mvc-2

3
推荐指数
1
解决办法
1968
查看次数

是否可以使用cout从用户定义的类型自动转换为std :: string?

在问题中,如果我在我的类中定义一个字符串运算符:

class Literal {
  operator string const () {
    return toStr ();
  };

  string toStr () const;
};
Run Code Online (Sandbox Code Playgroud)

然后我用它:

Literal l1 ("fa-2bd2bc3e0");
cout << (string)l1 << " Declared" << endl;
Run Code Online (Sandbox Code Playgroud)

使用显式转换一切正常,但如果我删除(字符串)编译器说它需要在std :: string中声明的强制转换运算符.它不应该自动投射我的类型?解决:我正在重载运算符<<(ostream&os,const Literal&l).

c++ casting stdstring user-defined-types implicit-cast

3
推荐指数
2
解决办法
1926
查看次数

C#隐式转换"重载"和反射问题

我遇到以下代码的问题(编译但崩溃):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace ConsoleApplication1
{
    public struct MyBoolean
    {
        public bool Value { get; set; }

        //cast string -> MyBoolean
        public static implicit operator MyBoolean(System.String value)
        {
            return new MyBoolean() { Value = (value[0] == 'J') };
        }

        //cast bool -> MyBoolean
        public static implicit operator MyBoolean(bool value)
        {
            return new MyBoolean() { Value = value };
        }

        //cast MyBoolean -> bool
        public static implicit operator bool(MyBoolean value)
        {
            return value.Value; …
Run Code Online (Sandbox Code Playgroud)

c# reflection implicit-cast

3
推荐指数
1
解决办法
1357
查看次数

隐式转换运算符和相等运算符

假设我有一个简单的对象支持对System.String的隐式转换

public sealed class CompanyCode
{
    public CompanyCode(String value)
    {
        // Regex validation on value format
        _value = value;
    }

    private readonly String _value;

    public override String ToString()
    {
        return _value;
    }

    static public implicit operator String(CompanyCode code)
    {
        if(code == null)
            return null;

        return code.ToString();
    }
}
Run Code Online (Sandbox Code Playgroud)

现在让我们说我的程序的另一部分我用字符串进行比较:

var companyCode = { some company code object }

if (companyCode == "MSFTUKCAMBS")
    // do something...
Run Code Online (Sandbox Code Playgroud)

编译器对==运算符做了什么?是否隐式将companyCode转换为字符串并运行System.String ==实现?它是否正在使用System.Object ==实施?或者编译器会抱怨我?(我现在没有编译器来检查这个).

据我所知,我还有其他几种选择.

  • ==(String x)在CompanyCode上实现运算符.
  • IEquatable<String>在CompanyCode上实现接口. …

c# operator-overloading implicit-cast implicit-conversion

3
推荐指数
1
解决办法
2791
查看次数

具有泛型的C#隐式运算符

我正在用C#编写枚举的抽象包装(我想要类似Vala中的枚举的东西)。我的代码是:

    public abstract class Wraper<T, TE>
        where T : Wraper<T, TE>, new()
    {
        public TE Value;

        public static implicit operator T(TE value)
        {
            return new T() { Value = value };
        }

        public static implicit operator TE(T value)
        {
            return value.Value;
        }
    }
Run Code Online (Sandbox Code Playgroud)

我想做这样的事情:

    public enum EFoo { A, B, C, D, E};
    public class Foo : Wraper<Foo, EFoo>
    {
        public bool IsBla
        {
            get { return Value == EFoo.A || Value == EFoo.E; }
        }
    }

    ...

    Foo foo …
Run Code Online (Sandbox Code Playgroud)

c# generics implicit-cast

3
推荐指数
1
解决办法
3890
查看次数