请考虑以下代码:
public class TextType {
public TextType(String text) {
underlyingString = text;
}
public static implicit operator String(TextType text) {
return text.underlyingString;
}
private String underlyingString;
}
TextType text = new TextType("Something");
String str = text; // This is OK.
Run Code Online (Sandbox Code Playgroud)
但是如果可能的话,我希望能够做到以下几点.
TextType textFromStringConstant = "SomeOtherText";
Run Code Online (Sandbox Code Playgroud)
我无法使用TextType隐式运算符重载扩展String类,但有没有办法将文字字符串分配给另一个类(由方法或其他东西处理)?
String是一个引用类型,因此当他们开发C#时,他们显然必须使用某种方式来获取类的字符串文字.我只是希望它不是硬编码的语言.
使用隐式运算符有什么问题,如下所示:
//linqpad c# program example
void Main()
{
var testObject = new MyClass<int>() { Value = 1 };
var add = 10 + testObject; //implicit conversion to int here
add.Dump(); // 11
}
class MyClass<T>
{
public T Value { get; set; }
public static implicit operator T (MyClass<T> myClassToConvert)
{
return myClassToConvert.Value;
}
}
Run Code Online (Sandbox Code Playgroud)
我想我可以这样对待为对象的值类型的实例,但看到我从来没有见过这样我想也许有一个理由的例子并不做这样的事情,有人能指出?
在我实际的代码,我想这样的数据抽象层的一部分,这样我就可以用信息返回对象描述的基础数据,但允许逻辑代码把它当作一个值类型时都需要知道是值,同时保持一切美观,并与泛型类型安全.
考虑一下这段代码
struct A {};
struct B { B(const A&) {} };
void f(B)
{
cout << "f()"<<endl;
}
void g(A &a)
{
cout << "g()" <<endl;
f(a); //a is implicitly converted into B.
}
int main()
{
A a;
g(a);
}
Run Code Online (Sandbox Code Playgroud)
这编译正常,运行良好.但如果我f(B)改为f(B&),它就不会编译.如果我写f(const B&),它再次编译好,运行正常.原因和理由是什么?
摘要:
void f(B); //okay
void f(B&); //error
void f(const B&); //okay
Run Code Online (Sandbox Code Playgroud)
我希望听到语言规范中的原因,理由和参考,以及每种情况.当然,功能签名本身并不正确.而是A隐式地转换为B和const B&,但不会转换为B&导致编译错误.
我有一个这样的集合类:
public class SomeDataCollection : List<ISomeData>
{
// some method ...
}
Run Code Online (Sandbox Code Playgroud)
但我不能这样做:
SomeDataCollection someDatas = new List<ISomeData>();
Run Code Online (Sandbox Code Playgroud)
无法隐式转换
List<ISomeData>为SomeDataCollection.存在显式转换(您是否错过了演员?)
所以我尝试在SomeDataCollection集合类中创建一个隐式的转换器:
public static implicit operator SomeDataCollection(List<ISomeData> l)
{
var someDatas = new SomeDataCollection();
someDatas.AddRange(l);
return someDatas;
}
Run Code Online (Sandbox Code Playgroud)
但它说我不能创建这样的转换器:
SomeDataCollection.implicit operator SomeDataCollection(List<ISomeData>):不允许在基类之间进行用户定义的转换
当我这样投出时:
SomeDataCollection someDatas = (SomeDataCollection)new List<ISomeData>();
Run Code Online (Sandbox Code Playgroud)
它抛出一个错误,说:
System.InvalidCastException:无法将类型的对象强制转换
List<ISomeData>为类型SomeDataCollection.
我怎样才能做到这一点:
SomeDataCollection someDatas = new List<ISomeData>();
Run Code Online (Sandbox Code Playgroud)
没有收到错误?请帮忙.提前致谢.
让我们假设将这两个等价表达式传递给Scala宏:
1+"foo"any2stringadd(1)+"foo"有没有办法在宏内区分这两个?
在我的Scala代码中,我有一些隐式转换,我有必要的导入存在:
import scala.language.implicitConversions
Run Code Online (Sandbox Code Playgroud)
但是,有时当在此之后再进行另一次导入时,我会收到警告,好像导入根本不存在:
警告:(112,18)隐式转换方法pair2Dimension应该通过使隐式值scala.language.implicitConversions可见来启用.
build.sbt:
name := "ImplicitSBT"
version := "1.0"
scalaVersion := "2.11.5"
scalacOptions ++= Seq("-deprecation","-feature")
libraryDependencies += "org.scala-lang.modules" %% "scala-swing" % "1.0.1"
Run Code Online (Sandbox Code Playgroud)
Main.scala:
import scala.language.implicitConversions
import scala.swing.{Action, _}
object Main extends App {
implicit def pair2Dimension(pair: (Int, Int)): Dimension = new Dimension(pair._1, pair._2)
val dim : Dimension = (0,0)
println(dim)
}
Run Code Online (Sandbox Code Playgroud)
为什么会这样?如何import scala.swing.{Action, _}隐藏implicitConversions导入?
我喜欢隐含的定义.它们使代码看起来很好,它们使用户觉得某些特性在类只是一个隐式定义时自然可用.然而,我在考虑JS原型,你可以基本上在你没写的类上定义一个方法.但是如果在下一个版本中,这个类定义了一个具有相同签名的方法并对其行为做出假设,那么你就搞砸了.
Scala的含义使得几乎完全相同,只有一个主要区别:隐式定义是作用域的,因此类的作者不会有通过其他人的代码中的隐式定义注入代码的风险.但是用户的代码怎么样?是否可以保护他免受课堂上的变化?
我们考虑一下这段代码:
class HeyMan {
def hello = println("Hello")
}
object Main extends App {
val heyMan = new HeyMan
implicit class ImplicitHeyMan(heyMan: HeyMan) {
def hello = println("What's up ?")
}
heyMan.hello // prints Hello
}
Run Code Online (Sandbox Code Playgroud)
很糟糕,不是吗?对我来说,正确的行为应该是隐式定义总是隐藏真实定义,以便保护用户代码免受他所调用的API中新方法的出现.
你怎么看 ?有没有办法让它安全或者我们应该停止使用这种方式吗?
我正在尝试使用C#泛型和基于此答案的策略模式实现类似c ++的模板
这是模式的一个示例:
interface ISomePolicy<T,U>
{
void _doSomething(U u);
}
class MyClass<T,U>:
ISomePolicy<int, double>,
ISomePolicy<int, int>
{
internal T myElement {get;set;}
public MyClass(T Element) {
myElement = Element;
}
void ISomePolicy<int, double>._doSomething(double u)
{
Console.WriteLine("this is int, double");
}
void ISomePolicy<int, int>._doSomething(int u)
{
Console.WriteLine("this is int, int");
}
}
static class MyClassExtension
{
//What I want to do
public static void doSomething<P, T, U>(this P oTh, U u) where P : MyClass<T, U>, ISomePolicy<T, U>
{
oTh._doSomething(u); …Run Code Online (Sandbox Code Playgroud) c# generics extension-methods template-specialization implicit-conversion
我正在尝试摆脱有损隐式转换的代码库,因此正在使用-Wconversionclang ++下的标记进行编译。以下代码预期会输出警告,但不会输出。
#include <cstddef>
#include <iostream>
#include <limits>
#include <optional>
int main() {
size_t x = std::numeric_limits<size_t>::max();
std::cout << x << std::endl;
auto x2 = std::make_optional<uint8_t>(x);
std::cout << (int)*x2 << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在make_optional生产线上,我size_t无声地缩小为a uint8_t。uint8_t x2 = x;例如,如果我写,我得到了预期的缩小转换警告。
当我使用std::optional构造函数时,也会发生这种情况。在我给出的代码中,调用了make_optional重载2,该调用调用了可选的构造函数重载6。这构造了Optional,就好像直接初始化包含的值一样,并且直接初始化不会引发隐式变窄转换警告。
除了编写optional自己的不隐藏缩小转换的类之外,还有什么方法可以使上述代码引发缩小转换警告?
与一起编译,/permissive但与一起失败/permissive-。什么不符合以及如何解决?
为什么很好,(2)但失败了?如果我删除它也很好。(4)(3)operator long
如何在不更改呼叫站点的情况下进行修复(3,4)?
#include <string>
struct my
{
std::string myVal;
my(std::string val): myVal(val) {}
operator std::string() { return myVal; };
operator long() { return std::stol(myVal); };
};
int main()
{
struct MyStruct
{
long n = my("1223"); // (1)
std::string s = my("ascas"); // (2)
} str;
str.s = my("ascas"); // (3)
str.n = my("1223"); // (4)
}
Run Code Online (Sandbox Code Playgroud)
错误信息
error C2593: 'operator =' is ambiguous
xstring(2667): note: could …Run Code Online (Sandbox Code Playgroud) c++ visual-c++ implicit-conversion move-constructor move-assignment-operator
c# ×4
c++ ×3
scala ×3
generics ×2
implicit ×2
.net-4.0 ×1
clang++ ×1
import ×1
operators ×1
reference ×1
scala-2.10 ×1
scala-macros ×1
string ×1
visual-c++ ×1
warnings ×1