我想让一个 oracle 对象返回自身并能够链接这些调用。我怎么做?
我试过返回相同的类型,但它不起作用,我也尝试添加一个由函数调用的过程,但它也不起作用。总是提示修改宽度成员的值。看起来函数不会承认副作用吗?它们是根据更数学的函数原理建模的吗?这是可以实现的吗?。我想我可以编写这个函数,让它用 SELF 构建一个新的矩形,但这是太多的工作。
我的目标是能够链接像 jQuery 或一些 java 类(单例?)这样的调用。就像是:r := r.setWidth(0).setWidth(1).setWidth(2);
当然,它会有更多的方法,它不会是一个矩形。这是错误:
Error: PLS-00363: expression 'SELF' cannot be used as an assignment target
Line: 18
Text: stWidth(w);
——
CREATE OR REPLACE TYPE rectangle AS OBJECT
(
-- The type has 3 attributes.
length NUMBER,
width NUMBER,
area NUMBER,
-- Define a constructor that has only 2 parameters.
CONSTRUCTOR FUNCTION rectangle(length NUMBER, width NUMBER)
RETURN SELF AS RESULT,
MEMBER FUNCTION setWidth(w NUMBER) RETURN rectangle,
MEMBER PROCEDURE stWidth(w NUMBER)
)
——
CREATE OR REPLACE TYPE BODY rectangle AS
CONSTRUCTOR FUNCTION rectangle(length NUMBER, width NUMBER)
RETURN SELF AS RESULT
AS
BEGIN
SELF.length := length;
SELF.width := width;
-- We compute the area rather than accepting it as a parameter.
SELF.area := length * width;
RETURN;
END;
MEMBER PROCEDURE stWidth(w NUMBER) IS
BEGIN
self.width := w;
END;
MEMBER FUNCTION setWidth(w NUMBER) RETURN rectangle IS
BEGIN
stWidth(w);
RETURN SELF;
END;
END;
提前致谢。
最佳答案
您不能同时更改对象和分配给它。您已经知道解决方案,“用 SELF 构建一个新的矩形”。但这不会是很多工作。
替换这个:
MEMBER FUNCTION setWidth(w NUMBER) RETURN rectangle IS
BEGIN
stWidth(w);
RETURN SELF;
END;
有了这个:
MEMBER FUNCTION setWidth(w NUMBER) RETURN rectangle IS
v_rectangle rectangle := self;
BEGIN
v_rectangle.width := w;
RETURN v_rectangle;
END;
您实际上收到了编译错误。默认情况下,
SELF
是 IN
范围。调用 stWidth
失败,因为它正在修改 IN
参数与 self.width := w;
.见:http://docs.oracle.com/cd/B28359_01/appdev.111/b28371/adobjbas.htm#CHDCFEEE
SELF is always the first parameter passed to the method.
In member functions, if SELF is not declared, its parameter mode defaults to IN.
In member procedures, if SELF is not declared, its parameter mode defaults to IN OUT. The default behavior does not include the NOCOPY compiler hint.
关于oracle - 如何在返回 SELF 的函数的 pl/sql 对象类型中链接调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18086603/